时间戳:格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总时间。(中国为东8区 )
Unix时间戳转DateTime:
public static DateTime ConvertToDateTime(string timestamp)
{
DateTime time = DateTime.MinValue;
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
if (timestamp.Length == 10) //精确到秒
{
time = startTime.AddSeconds(double.Parse(timestamp));
}
else if (timestamp.Length == 13) //精确到毫秒
{
time = startTime.AddMilliseconds(double.Parse(timestamp));
}
return time;
}
DateTime转时间戳:
public static string ConvertTimestamp(DateTime time, int type = 0)
{
double intResult = 0;
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
if (type == 0)
{
intResult = (time - startTime).TotalMilliseconds;
}
else if (type == 1)
{
intResult = (time - startTime).TotalSeconds;
}
else
{
Console.WriteLine("参数错误!");
}
return Math.Round(intResult, 0).ToString();
}
Tips:注意北京时间和格林威治时间