这里记录一个时间戳的互相转换方法,网上都找了,基本都没有精确到毫秒,我的这个基本可以满足精确到毫秒的级别,代码如下:
1 ///2 /// Unix时间戳转换为DateTime 3 /// 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 try11 {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 ///22 /// DateTime转换为Unix时间戳23 /// 24 /// 25 ///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 :-);