go 序列化反序列化之後時區信息丟失

  •  編寫了獲取當前datetime 時間的方法如下
    // GetCurrentDateString 獲取當天的時間date
    func GetCurrentDateString() time.Time {
        // 獲取當前時間
        currentTime := time.Now().Local()
        // 格式化日期爲字符串
        dateString := currentTime.Format(time.DateTime)
        resultTime, _ := time.Parse(time.DateTime, dateString)
        return resultTime
    }

    插入db之後發現時間+8了。

  • 造成以上原因是因爲反序列化之後時區信息丟失了。所以沒有時區的時候time到db用的是國際時間。所以跟北京/上海時間大致會相差8h
  • 解決方案 反序列化的時候代碼改成 : 
    // GetCurrentDateString 獲取當天的時間date
    func GetCurrentDateString() time.Time {
        // 獲取當前時間
        currentTime := time.Now().Local()
        // 格式化日期爲字符串
        dateString := currentTime.Format(time.DateTime)
        resultTime, _ := time.ParseInLocation(time.DateTime, dateString, time.Local)
        return resultTime
    }

     

  • 如果時間字符串中帶了時區信息纔去使用 time.Parse,否則使用 time.ParseInLocation
  • 排查db 和本地時間對不上的思路方案:
    • 檢查鏈接字符串是否添加時區信息  例如 : parseTime=true&loc=Local
    • 檢查服務器當前時區 是否正確: timedatectl | grep "Time zone"
    • 檢查mysql 時區設置:SHOW VARIABLES LIKE '%time_zone%';
    • 阿里雲AnalyticDB實例Datatime 類型最多精確到秒。使用TIMESTAMP可以存儲'2024-03-11 15:22:11.4688249' 。 使用起來和Mysql實例有差距
    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章