golang 時間missing Location in call to Date
阿新 • • 發佈:2021-11-19
golang使用"Asia/Shanghai"時區轉換時間格式報:missing Location in call to Date
當然解決方法1是:time.FixedZone
//os.Setenv("ZONEINFO","D:\\ProgramFiles\\Go\\lib\\time\\zoneinfo") loc, err := time.LoadLocation("Asia/Shanghai") //設定時區 if err != nil { loc = time.FixedZone("CST-8", 8*3600) } fmt.Print(loc)
解決方法二是:os.Setenv("ZONEINFO","xxx") 值可以是那個zip檔案,也可以是一個目錄,比如把zip解壓後的目錄,我這是解壓zoneinfo.zip,【我的問題是,公司強制安裝一個軟體,會加密電腦上的word ,txt,zip 等檔案,導致讀出來的zip 檔案頭有問題】
原始碼如下【1.15.6版本,省略了一些無關的的程式碼】
func LoadLocation(name string) (*Location, error) { ....... zoneinfoOnce.Do(func() { env, _ := syscall.Getenv("ZONEINFO") zoneinfo = &env }) var firstErr error if *zoneinfo != "" { if zoneData, err := loadTzinfoFromDirOrZip(*zoneinfo, name); err == nil { if z, err := LoadLocationFromTZData(name, zoneData); err == nil { return z, nil } firstErr= err } else if err != syscall.ENOENT { firstErr = err } } ...... return nil, firstErr } func loadTzinfoFromDirOrZip(dir, name string) ([]byte, error) { if len(dir) > 4 && dir[len(dir)-4:] == ".zip" { return loadTzinfoFromZip(dir, name) } if dir != "" { name = dir + "/" + name } return readFile(name) } // loadTzinfoFromZip returns the contents of the file with the given name // in the given uncompressed zip file. func loadTzinfoFromZip(zipfile, name string) ([]byte, error) { fd, err := open(zipfile) if err != nil { return nil, err } defer closefd(fd) .................................... buf := make([]byte, ztailsize) if err := preadn(fd, buf, -ztailsize); err != nil || get4(buf) != zecheader { return nil, errors.New("corrupt zip file " + zipfile) } ................................. return nil, syscall.ENOENT }
方法呼叫路線如下:
zip: LoadLocation->loadTzinfoFromDirOrZip->loadTzinfoFromZip->get4
路徑 : LoadLocation->loadTzinfoFromDirOrZip->readFile
如果是zip,方法get4會驗證zip檔案頭。我這裡有公司軟體加密,所以zip 情況下get4方法錯誤,所以改為路徑
windows技術愛好者