using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 时间戳demo
{

/*
* Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、
* POSIX时间(POSIX time),是一种时间表示方式,
*
* 定义为从格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
* **/
class Program
{
static void Main(string[] args)
{

string timeStamp = GetTimeStamp();
Console.WriteLine(GetTimeStamp());

DateTime currentDate = GetTime( timeStamp);
string datestring = currentDate.ToString("yyyy-MM-dd HH:mm:ss fff");
Console.WriteLine(datestring);

Console.ReadKey();
}

/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}

/// <summary>
/// DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time"> DateTime时间格式</param>
/// <returns>Unix时间戳格式</returns>
public static int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}

/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式</param>
/// <returns>C#格式时间</returns>
public static DateTime GetTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
}
}