【.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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM