这里记录一个时间戳的互相转换方法,网上都找了,基本都没有精确到毫秒,我的这个基本可以满足精确到毫秒的级别,代码如下:
1 /// <summary> 2 /// Unix时间戳转换为DateTime 3 /// </summary> 4 private DateTime ConvertToDateTime(string timestamp) 5 { 6 System.DateTime time = System.DateTime.MinValue; 7 //精确到毫秒 8 //时间戳转成时间 9 DateTime start = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 10 try 11 { 12 time = timestamp.Length == 10 ? start.AddSeconds(long.Parse(timestamp)) : start.AddMilliseconds(long.Parse(timestamp)); 13 } 14 catch (Exception ex) 15 { 16 return start;//转换失败 17 } 18 return time; 19 } 20 21 /// <summary> 22 /// DateTime转换为Unix时间戳 23 /// </summary> 24 /// <param name="time"></param> 25 /// <returns></returns> 26 private string ConvertTimestamp(DateTime time) 27 { 28 double intResult = 0; 29 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 30 intResult = (time - startTime).TotalMilliseconds; 31 return Math.Round(intResult,0).ToString(); 32 }
特此标记,希望对有帮助的人少走弯路。ths :-);
时间: 2024-10-19 11:35:14