C#实现DateTime与Unix 时间戳(long)互转
1 /// <summary> 2 /// 将 DateTime 转换为 Unix 时间戳 3 /// </summary> 4 /// <param name="dateTime">需要转换的时间</param> 5 /// <returns>Unix 时间戳</returns> 6 public static long DateTimeToUnixTime(DateTime dateTime) 7 { 8 return (long)(dateTime - TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0), TimeZoneInfo.Local)).TotalSeconds; 9 }
1 /// <summary> 2 /// 将 Unix 时间戳转换为 DateTime 3 /// </summary> 4 /// <param name="timestamp">Unix 时间戳</param> 5 /// <returns>需要转换的时间</returns> 6 public static DateTime UnixTimeToDateTime(long timestamp) 7 { 8 if (timestamp < 0) 9 throw new ArgumentOutOfRangeException("timestamp is out of range"); 10 11 return TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0), TimeZoneInfo.Local).AddSeconds(timestamp); 12 }