File: tz.go

package info (click to toggle)
golang-github-thlib-go-timezone-local 0.0~git20210907.ef149e4-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 228 kB
  • sloc: makefile: 4
file content (42 lines) | stat: -rw-r--r-- 830 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package tzlocal

import (
	"fmt"
	"os"
	"time"
)

// EnvTZ will return the TZ env value if it is set, go will revert any invalid timezone to UTC
func EnvTZ() (string, bool) {
	if name, ok := os.LookupEnv("TZ"); ok {
		// Go treats blank as UTC
		if name == "" {
			return "UTC", true
		}
		_, err := time.LoadLocation(name)
		// Go treats invalid as UTC
		if err != nil {
			return "UTC", true
		}
		return name, true
	}
	return "", false
}

// RuntimeTZ get the full timezone name of the local machine
func RuntimeTZ() (string, error) {

	// Get the timezone from the TZ env variable
	if name, ok := EnvTZ(); ok {
		return name, nil
	}

	// Get the timezone from the system file
	name, err := LocalTZ()
	if err != nil {
		err = fmt.Errorf("failed to get local machine timezone: %w", err)
		return "", err
	}

	return name, err
}