zoukankan      html  css  js  c++  java
  • 【.net Core】DateTime在Linux中与Windows时间不一致

    项目在windows中请求接口正常,换到linux服务器上就提示错误,跟断点看了下原来是token验证被挡住了,两者时间相差8小时。怀疑是linux时间有问题,使用date查看服务器时间显示:

     确实是本地时间。

    当然还有linux服务器本身时间不是CST,而是UTC格式的,可百度搜索:修改区时UTC改为CST

    后来经过排查和百度发现是docker在捣蛋,这里直接贴出解决方案

    1、在项目中新增时间转化类

    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();
            }
        }
    View Code

    使用:DateTime.Now.ToCstTime();

    传送门:https://www.cnblogs.com/1175429393wljblog/p/11692610.html

    ps:此种方式没有实践

    2、在docker中做文章,将linux服务器时间拷贝到docker容器中

    a、在dockerfile中添加时间拷贝语句  【此方法是我选择的,一劳永逸】

    #时区设置
    RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 
    && echo ‘Asia/Shanghai’ >/etc/timezone

    还有b和c方法,没有测试可在博主原文中查看试用

    传送门:https://www.skyfinder.cc/2018/12/14/dockerandhostdatetimenotsame

  • 相关阅读:
    移动端开发-禁止横屏
    奇葩的对象创建方式(更新中)
    每日积累之8.8
    每日积累 8.6
    折半查找
    linux中的amount的解释
    Redis集群错误
    每日积累 8.6
    Redis中在程序中的应用
    每日积累 8.4
  • 原文地址:https://www.cnblogs.com/yhnet/p/12971692.html
Copyright © 2011-2022 走看看