int UTCSecond = (int)((DateTimeOffset)DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local)).ToUnixTimeSeconds(); DateTime time = DateTimeOffset.FromUnixTimeSeconds(UTCSecond).DateTime; Console.WriteLine("当前utc:{0},秒数:{1},换算时间:{2}", DateTimeOffset.Now, UTCSecond, time.ToString("F")); UTCSecond = Q.Helper.TimeHelper.ToUTCSecond(DateTime.Now); time = DateTimeOffset.FromUnixTimeSeconds(UTCSecond).DateTime; Console.WriteLine("当前utc:{0},秒数:{1},换算时间:{2}", DateTimeOffset.Now, UTCSecond, time.ToString("F")); Console.Read(); |
QCOMMON请使用NUGET包管理器搜索安装 QCommon
基本原理如下
/// <summary> /// 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(); } |