C#时间戳和DateTime转换

时间戳:格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总时间。(中国为东8区 )

Unix时间戳转DateTime:

 1         /// <summary>
 2         /// Unix时间戳转DateTime
 3         /// </summary>
 4         /// <param name="timestamp">时间戳</param>
 5         /// <returns></returns>
 6         public static DateTime ConvertToDateTime(string timestamp)
 7         {
 8             DateTime time = DateTime.MinValue;
 9             DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1));
10             if (timestamp.Length==10)        //精确到秒
11             {
12                 time=startTime.AddSeconds(double.Parse(timestamp));
13             }
14             else if (timestamp.Length ==13)   //精确到毫秒
15             {
16                 time = startTime.AddMilliseconds(double.Parse(timestamp));
17             }
18             return time;
19         }

DateTime转时间戳:

 1         /// <summary>
 2         /// DateTime转时间戳
 3         /// </summary>
 4         /// <param name="time">DateTime时间</param>
 5         /// <param name="type">0为毫秒,1为秒</param>
 6         /// <returns></returns>
 7         public static string ConvertTimestamp(DateTime time,int type=0)
 8         {
 9             double intResult = 0;
10             DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
11             if (type==0)
12             {
13                 intResult = (time - startTime).TotalMilliseconds;
14             }
15             else if (type == 1)
16             {
17                 intResult = (time - startTime).TotalSeconds;
18             }
19             else
20             {
21                 Console.WriteLine("参数错误!");
22             }
23             return Math.Round(intResult, 0).ToString();
24         }

 Tips:注意北京时间和格林威治时间

posted @ 2020-07-08 11:13  MarioLz  阅读(5085)  评论(0编辑  收藏  举报