Home >Backend Development >Golang >How to Get a List of All Valid Time Zones in Go?

How to Get a List of All Valid Time Zones in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 15:40:11532browse

How to Get a List of All Valid Time Zones in Go?

How to Obtain a List of Valid Time Zones in Go

In programming, selecting the appropriate time zone for various operations can be crucial. In Go, you may encounter scenarios where you need to populate an array with commonly accepted time zones for use in selecting a user's preferred time zone. This article will guide you through a comprehensive solution to this problem.

Solution

To acquire a list of time zones in Go, consider leveraging the following approach:

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:])
        }
    }
}

Output

The sample code will output a comprehensive list of valid time zones. Here's a snippet of the output:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
...

Usage

You can utilize this list to populate an array or a drop-down menu for your HTML template. By providing users with a selection of time zones, they can select the one most relevant to their location, ensuring accurate time-keeping in your application.

The above is the detailed content of How to Get a List of All Valid Time Zones in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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