• DOTNET CORE DATETIME在LINUX与WINDOWS时间不一致


    .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()
  • 相关阅读:
    【Appium】appium踩坑记录:解决每次安装appium setting和Unlock
    Pycharm from XXX import XXX 引入本地文件标红报错(source_path&Python package)
    🍖02 不同平台更换pip源
    🍖pycharm 更换 pip 下载源
    🍖01 路飞学城项目分析
    🍖Vue-cli 创建项目
    🍖Vue 与后端交互
    🍖Vue 计算属性
    🍖Vue 虚拟DOM与Diff算法简介
    🍖Vue 生命期钩子
  • 原文地址:https://www.cnblogs.com/asd14828/p/10773737.html
Copyright © 2020-2023  润新知