.net core項目,部署到CentOS上的時候,發現DateTime.Now獲取的時間與Windows不一致,主要是時區不一致。
static void Main(string[] args) { Console.WriteLine(DateTime.Now); }
CentOS的時區配置如下:
[root@localhost ~]# timedatectl status Local time: 五 2019-04-26 13:01:02 CST Universal time: 五 2019-04-26 05:01:02 UTC RTC time: 五 2019-04-26 13:01:01 Time zone: Asia/Shanghai (CST, +0800) NTP enabled: n/a NTP synchronized: no RTC in local TZ: yes DST active: n/a Warning: The system is configured to read the RTC time in the local time zone. This mode can not be fully supported. It will create various problems with time zone changes and daylight saving time adjustments. The RTC time is never updated, it relies on external facilities to maintain it. If at all possible, use RTC in UTC by calling 'timedatectl set-local-rtc 0'.
CentOS上的本地時間也是北京時間,為什么dotnet core程序獲取到的時間卻相對北京時間少了8個小時?
猜測問題可能是dotnet core程序的DateTime在Linux平台獲取到錯誤的時區了。
google發現,dotnet core在Windows和Linux上使用的時區不同,在Windows上使用的是Windows time zone IDs,但是在*nix系統上使用的是IANA時區。
那么解決辦法是不管什么系統,統一使用IANA時區,可以通過一個第三方庫NodaTime來實現。
添加依賴包:NodaTime
將系統的當前時間換算成CST標准時間的工具方法
public class TimeUtil { public static DateTime GetCstDateTime() { Instant now = SystemClock.Instance.GetCurrentInstant(); var shanghaiZone = DateTimeZoneProviders.Tzdb["Asia/Shanghai"]; return now.InZone(shanghaiZone).ToDateTimeUnspecified(); } }
然后寫一個DateTime的擴展方法:
public static class DateTimeExtentions { public static DateTime ToCstTime(this DateTime time) { return TimeUtil.GetCstDateTime(); } }
所有系統里面獲取時間都通過如下方法,即可實現在Windows和Linux系統上都獲取到同樣的北京時間:
DateTime.Now.ToCstTime()