int UTCSecond = (int)((DateTimeOffset)DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local)).ToUnixTimeSeconds(); this DateTime time = DateTimeOffset.FromUnixTimeSeconds(UTCSecond).DateTime; spa Console.WriteLine("當前utc:{0},秒數:{1},換算時間:{2}", DateTimeOffset.Now, UTCSecond, time.ToString("F")); blog UTCSecond = Q.Helper.TimeHelper.ToUTCSecond(DateTime.Now); ci time = DateTimeOffset.FromUnixTimeSeconds(UTCSecond).DateTime; it Console.WriteLine("當前utc:{0},秒數:{1},換算時間:{2}", DateTimeOffset.Now, UTCSecond, time.ToString("F")); table Console.Read();原理 |
QCOMMON請使用NUGET包管理器搜索安裝 QCommon date
基本原理以下 搜索
/// <summary> rsa /// UTC時間 /// </summary> static readonly DateTime UTC = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Utc); /// <summary> /// 時間轉UTC秒 /// </summary> /// <param name="dateTime">時間(當前時區)</param> /// <returns>UTC秒</returns> public static int ToUTCSecond(this DateTime dateTime) { return (int)dateTime.ToUniversalTime().Subtract(UTC).TotalSeconds; }
/// <summary> /// UTC秒轉當地時間 /// </summary> /// <param name="second">秒數</param> /// <returns>當時時間</returns> public static DateTime ToDateTime(this int second) { return UTC.AddSeconds(second).ToLocalTime(); } |