C#使用各種時間戳及轉換
阿新 • • 發佈:2021-10-20
C#使用各種時間戳及轉換
/// <summary> /// DateTime時間格式轉換為13位帶毫秒的Unix時間戳 /// </summary> /// <param name="time">DateTime時間格式</param> /// <returns>Unix時間戳格式</returns> public static long ConvertDateTimeLong(DateTime time) { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); return (long)(time - startTime).TotalMilliseconds; } /// <summary> /// DateTime時間格式轉換為10位不帶毫秒的Unix時間戳 /// </summary> /// <param name="time">DateTime時間格式</param> /// <returns>Unix時間戳格式</returns> public static long ConvertDateTimeInt(DateTime time) { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); return (long)(time - startTime).TotalSeconds; } /// <summary> /// 時間戳轉為C#格式時間 /// </summary> /// <param name="timeStamp">Unix時間戳格式</param> /// <returns>C#格式時間</returns> public static DateTime GetTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); }