Get a list of valid time zones in Go

前端 未结 3 743
挽巷
挽巷 2020-12-31 13:16

I\'d like to write a method that will populate a Go Language array with the common timezones that are accepted by the time.Format() call, for use in an HTML tem

3条回答
  •  轮回少年
    2020-12-31 13:59

    Here is an example: https://play.golang.org/p/KFGQiW5A1P-

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "strings"
        "unicode"
    )
    
    func main() {
        fmt.Println(GetOsTimeZones())
    }
    
    func GetOsTimeZones() []string {
        var zones []string
        var zoneDirs = []string{
            // Update path according to your OS
            "/usr/share/zoneinfo/",
            "/usr/share/lib/zoneinfo/",
            "/usr/lib/locale/TZ/",
        }
    
        for _, zd := range zoneDirs {
            zones = walkTzDir(zd, zones)
    
            for idx, zone := range zones {
                zones[idx] = strings.ReplaceAll(zone, zd+"/", "")
            }
        }
    
        return zones
    }
    
    func walkTzDir(path string, zones []string) []string {
        fileInfos, err := ioutil.ReadDir(path)
        if err != nil {
            return zones
        }
    
        isAlpha := func(s string) bool {
            for _, r := range s {
                if !unicode.IsLetter(r) {
                    return false
                }
            }
            return true
        }
    
        for _, info := range fileInfos {
            if info.Name() != strings.ToUpper(info.Name()[:1])+info.Name()[1:] {
                continue
            }
    
            if !isAlpha(info.Name()[:1]) {
                continue
            }
    
            newPath := path + "/" + info.Name()
    
            if info.IsDir() {
                zones = walkTzDir(newPath, zones)
            } else {
                zones = append(zones, newPath)
            }
        }
    
        return zones
    }
    

提交回复
热议问题