Home > Backend Development > Golang > How Can I Get a List of Usable Time Zones for Go\'s time.Format()?

How Can I Get a List of Usable Time Zones for Go\'s time.Format()?

Patricia Arquette
Release: 2024-12-01 09:43:10
Original
738 people have browsed it

How Can I Get a List of Usable Time Zones for Go's time.Format()?

Getting a List of Usable Time Zones for Go's time.Format()

For providing users a convenient way to select time zones in your applications, you may need to populate a dropdown with a list of valid time zones. This list can be generated with a straightforward method in Go.

Solution:

To obtain a comprehensive list of commonly supported time zones that can be used with the time.Format() function, you can employ the following code:

package main

import (
    "fmt"
    "os"
    "strings"
)

var zoneDirs = []string{
    // Update path according to your OS
    "/usr/share/zoneinfo/",
    "/usr/share/lib/zoneinfo/",
    "/usr/lib/locale/TZ/",
}

var zoneDir string

func main() {
    for _, zoneDir = range zoneDirs {
        ReadFile("")
    }
}

func ReadFile(path string) {
    files, _ := os.ReadDir(zoneDir + path)
    for _, f := range files {
        if f.Name() != strings.ToUpper(f.Name()[:1]) + f.Name()[1:] {
            continue
        }
        if f.IsDir() {
            ReadFile(path + "/" + f.Name())
        } else {
            fmt.Println((path + "/" + f.Name())[1:])
        }
    }
}
Copy after login

Explanation:

  • This code loops through potential time zone directories to locate valid time zones.
  • It reads the directory contents and ignores entries with mixed casing.
  • If an entry is a directory, it recursively calls the ReadFile function to continue searching.
  • Time zone names are then printed without the leading slash.

Output:

Executing the code will produce a list of time zone names, such as:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
...
Copy after login

You can incorporate this list into your HTML template for a user-friendly time zone selection feature.

The above is the detailed content of How Can I Get a List of Usable Time Zones for Go\'s time.Format()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template