.net core項目,部署到CentOS上的時候,發現DateTime.Now獲取的時間與Windows不一致,主要是時區不一致。ide
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'.
public class TimeUtil { public static DateTime GetCstDateTime() { Instant now = SystemClock.Instance.GetCurrentInstant(); var shanghaiZone = DateTimeZoneProviders.Tzdb["Asia/Shanghai"]; return now.InZone(shanghaiZone).ToDateTimeUnspecified(); } }
而後寫一個DateTime的擴展方法:this
public static class DateTimeExtentions { public static DateTime ToCstTime(this DateTime time) { return TimeUtil.GetCstDateTime(); } }
全部系統裏面獲取時間都經過以下方法,便可實如今Windows和Linux系統上都獲取到一樣的北京時間:google
DateTime.Now.ToCstTime()