1 /// <summary> 2 /// 时间戳和日期的转化 3 /// </summary> 4 public class DateTimeUtility 5 { 6 /// <summary> 7 /// 日期转换为时间戳(时间戳单位秒) 8 /// </summary> 9 /// <param name="TimeStamp"></param> 10 /// <returns></returns> 11 public static long ConvertToTimeStamp(DateTime time) 12 { 13 DateTime Jan1st1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 14 return (long)(time.AddHours(-8) - Jan1st1970).TotalMilliseconds; 15 } 16 17 /// <summary> 18 /// 时间戳转换为日期(时间戳单位秒) 19 /// </summary> 20 /// <param name="TimeStamp"></param> 21 /// <returns></returns> 22 public static DateTime ConvertToDateTime(long timeStamp) 23 { 24 var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 25 return start.AddMilliseconds(timeStamp).AddHours(8); 26 } 27 28 }
如果是精确到秒级别的
把Milliseconds换成seconds即可。