Debian Codegraph @

tzlocal/tz_windows.go

raw symbols SCIP
1 package tzlocal
2
3 //go:generate go run ./../tzlocal/cmd/update_tzmapping.go
4
5 import (
6 "fmt"
7 "os/exec"
8 "strings"
9
10 "golang.org/x/sys/windows/registry"
11 )
12
13 const tzKey = `SYSTEM\CurrentControlSet\Control\TimeZoneInformation`
14 const tzKeyVal = "TimeZoneKeyName"
15
16 // LocalTZ obtains the name of the time zone Windows is configured to use. Returns the corresponding IANA standard name
17 func LocalTZ() (string, error) {
18 var winTZname string
19 var errTzutil, errReg error
20
21 // try tzutil command first - if that is not available, try to read from registry
22 winTZname, errTzutil = localTZfromTzutil()
23 if errTzutil != nil {
24 winTZname, errReg = localTZfromReg()
25 if errReg != nil { // both methods failed, return both errors
26 return "", fmt.Errorf("failed to read time zone name with errors\n(1) %s\n(2) %s", errTzutil, errReg)
27 }
28 }
29
30 if name, ok := WinTZtoIANA[winTZname]; ok {
31 return name, nil
32 }
33 return "", fmt.Errorf("could not find IANA tz name for set time zone \"%s\"", winTZname)
34 }
35
36 // localTZfromTzutil executes command `tzutil /g` to get the name of the time zone Windows is configured to use.
37 func localTZfromTzutil() (string, error) {
38 cmd := exec.Command("tzutil", "/g")
39 data, err := cmd.Output()
40 if err != nil {
41 return "", err
42 }
43 return strings.TrimSpace(string(data)), nil
44 }
45
46 // localTZfromReg obtains the time zone Windows is configured to use from registry.
47 func localTZfromReg() (string, error) {
48 k, err := registry.OpenKey(registry.LOCAL_MACHINE, tzKey, registry.QUERY_VALUE)
49 if err != nil {
50 return "", err
51 }
52 defer k.Close()
53
54 winTZname, _, err := k.GetStringValue(tzKeyVal)
55 if err != nil {
56 return "", err
57 }
58 return strings.TrimSpace(winTZname), nil
59 }