.net Core in Windows DateTime inconsistent with the time in Linux Docker

Recently wrote a .net core project, deployed to and running on CentOS docker and found time to get DateTime.Now inconsistent with Windows (timed task execution, late eight hours), on Windows you can get the right local time, acquired in Docker environment Linxu CentOS in less time eight hours. Check the machine time by Linxu command, the local time is correct, but the .net core is still small in Docker acquisition time is running eight hours. Speculation may be a problem area, and then to find a library NodaTime of time when obtaining a unified zone, which at the time of acquisition on the environment Linxu CentOS Docker's remains consistent with Windows.

Add an extension method DateTime:

public class TimeUtil
    {
        public static DateTime GetCstDateTime()
        {
            Instant now = SystemClock.Instance.GetCurrentInstant();
            var shanghaiZone = DateTimeZoneProviders.Tzdb["Asia/Shanghai"];
            return now.InZone(shanghaiZone).ToDateTimeUnspecified();
        }

    }
    public static class DateTimeExtentions
    {
        public static DateTime ToCstTime(this DateTime time)
        {
            return TimeUtil.GetCstDateTime();
        }
    }
   

  In the program acquisition time by a process can be realized to maintain unity in Windows and Linux:

DateTime.Now.ToCstTime();  
 
除了以上方式之外,可以将Linxu时间和Docker容器进行同步。具体详情,请参考。docker容器与Linux主机环境获取时间不一致

原文链接:https://www.skyfinder.cc/2018/10/01/dotnetcoredatetimenotunified/
Published 357 original articles · won praise 35 · views 280 000 +

Guess you like

Origin blog.csdn.net/LongtengGensSupreme/article/details/102608958