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