golang 時間missing Location in call to Date


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方法錯誤,所以改為路徑

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM