Skip to content

Commit dfc6ef6

Browse files
committed
use GetDynamicTimeZoneInformation and add example
1 parent 2a811fc commit dfc6ef6

5 files changed

Lines changed: 144 additions & 21 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
.idea
33
.DS_Store
44
tzdata/output.tar.gz
5+
/bin/

‎README.md‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,40 @@ fmt.Printf("Actual IANA name: %v\n", tzname) // Prints "Actual IANA name: Europe
3333
go get github.com/thlib/go-timezone-local/tzlocal
3434
```
3535

36-
### See it in action:
36+
### Included example
37+
38+
A runnable example is available in [`example/main.go`](./example/main.go). It prints the operating system, detected IANA time zone, and current local time.
39+
40+
The example imports [`time/tzdata`](https://pkg.go.dev/time/tzdata), so the IANA time zone database is embedded in the executable. This is useful for standalone Windows builds where a time zone database may not otherwise be available.
41+
42+
Run it from the repository root:
43+
44+
```sh
45+
go run ./example
46+
```
47+
48+
Build and run it on Linux:
49+
50+
```sh
51+
go build -o bin/timezone-example-linux ./example
52+
./bin/timezone-example-linux
53+
```
54+
55+
Cross-compile it for 64-bit Windows:
56+
57+
```sh
58+
GOOS=windows GOARCH=amd64 go build -o bin/timezone-example-windows-amd64.exe ./example
59+
```
60+
61+
Then run it from PowerShell on Windows:
62+
63+
```powershell
64+
.\bin\timezone-example-windows-amd64.exe
65+
```
66+
67+
The generated `bin/` directory is ignored by Git.
68+
69+
### Use in your own program
3770

3871
Open your project folder
3972
Create a file `main.go`

‎example/main.go‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"runtime"
7+
"time"
8+
_ "time/tzdata"
9+
10+
"github.com/thlib/go-timezone-local/tzlocal"
11+
)
12+
13+
func main() {
14+
timeZone, err := tzlocal.RuntimeTZ()
15+
if err != nil {
16+
fmt.Fprintln(os.Stderr, err)
17+
os.Exit(1)
18+
}
19+
20+
location, err := time.LoadLocation(timeZone)
21+
if err != nil {
22+
fmt.Fprintf(os.Stderr, "failed to load time zone %q: %v\n", timeZone, err)
23+
os.Exit(1)
24+
}
25+
26+
fmt.Printf("OS: %s\n", runtime.GOOS)
27+
fmt.Printf("Time zone: %s\n", timeZone)
28+
fmt.Printf("Local time: %s\n", time.Now().In(location).Format(time.RFC3339))
29+
}

‎tzlocal/tz_dynamic_windows.go‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package tzlocal
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
"syscall"
7+
"unsafe"
8+
)
9+
10+
const timeZoneIDInvalid = 0xffffffff
11+
12+
// dynamicTimeZoneInformation matches the Windows DYNAMIC_TIME_ZONE_INFORMATION
13+
// structure. It is declared here because the project's version of x/sys/windows
14+
// does not expose it.
15+
type dynamicTimeZoneInformation struct {
16+
Bias int32
17+
StandardName [32]uint16
18+
StandardDate syscall.Systemtime
19+
StandardBias int32
20+
DaylightName [32]uint16
21+
DaylightDate syscall.Systemtime
22+
DaylightBias int32
23+
TimeZoneKeyName [128]uint16
24+
DynamicDaylightTimeDisabled uint8
25+
}
26+
27+
var getDynamicTimeZoneInformation = syscall.NewLazyDLL("kernel32.dll").NewProc("GetDynamicTimeZoneInformation")
28+
29+
// localTZfromDynamicTimeZoneInformation obtains the Windows time zone key name
30+
// and whether dynamic daylight saving time is disabled. The procedure is
31+
// resolved at runtime because it is not available before Windows Vista.
32+
func localTZfromDynamicTimeZoneInformation() (string, bool, error) {
33+
if err := getDynamicTimeZoneInformation.Find(); err != nil {
34+
return "", false, err
35+
}
36+
37+
var info dynamicTimeZoneInformation
38+
result, _, callErr := getDynamicTimeZoneInformation.Call(uintptr(unsafe.Pointer(&info)))
39+
if uint32(result) == timeZoneIDInvalid {
40+
if callErr != syscall.Errno(0) {
41+
return "", false, callErr
42+
}
43+
return "", false, syscall.EINVAL
44+
}
45+
46+
name := strings.TrimSpace(syscall.UTF16ToString(info.TimeZoneKeyName[:]))
47+
if name == "" {
48+
return "", false, fmt.Errorf("GetDynamicTimeZoneInformation returned an empty time zone key name")
49+
}
50+
51+
return name, info.DynamicDaylightTimeDisabled != 0, nil
52+
}

‎tzlocal/tz_windows.go‎

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,9 @@ const tzDynamicDayLightDisabledKeyVal = "DynamicDaylightTimeDisabled"
1414

1515
// LocalTZ obtains the name of the time zone Windows is configured to use. Returns the corresponding IANA standard name
1616
func LocalTZ() (string, error) {
17-
var dstOff bool
18-
const dstOffSuffix = "_dstoff"
19-
20-
// try tzutil command first - if that is not available, try to read from registry
21-
winTZname, errTzUtil := localTZfromTzutil()
22-
if strings.HasSuffix(winTZname, dstOffSuffix) {
23-
winTZname = strings.TrimSuffix(winTZname, dstOffSuffix)
24-
dstOff = true
25-
}
26-
27-
// Try to read from registry
28-
if errTzUtil != nil {
29-
var errReg error
30-
winTZname, dstOff, errReg = localTZfromReg()
31-
if errReg != nil { // both methods failed, return both errors
32-
return "", fmt.Errorf("failed to read timezone from tzutil %s and registry %s", errTzUtil.Error(), errReg.Error())
33-
}
17+
winTZname, dstOff, err := localTZInfo()
18+
if err != nil {
19+
return "", err
3420
}
3521

3622
// Get the IANA time zone from the set time zone.
@@ -39,9 +25,8 @@ func LocalTZ() (string, error) {
3925
return "", fmt.Errorf("could not find IANA tz name for set time zone %q", winTZname)
4026
}
4127

42-
// Check if registry key `DynamicDaylightTimeDisabled` value is 0,
43-
// which indicates that "Daylight Saving Time" adjustments for the timezone are disabled.
44-
// Don't return the timezone name, instead return Etc/GMT+offset.
28+
// If daylight saving time adjustments are disabled, return a fixed-offset
29+
// zone instead of one that applies the IANA zone's DST transitions.
4530
if dstOff {
4631
location, err := time.LoadLocation(timezone)
4732
if err != nil {
@@ -72,6 +57,29 @@ func LocalTZ() (string, error) {
7257
return timezone, nil
7358
}
7459

60+
// localTZInfo obtains the Windows time zone name and whether daylight saving
61+
// time is disabled, falling back from the Windows API to tzutil and registry.
62+
func localTZInfo() (string, bool, error) {
63+
winTZname, dstOff, errDynamic := localTZfromDynamicTimeZoneInformation()
64+
if errDynamic == nil {
65+
return winTZname, dstOff, nil
66+
}
67+
68+
winTZname, errTzUtil := localTZfromTzutil()
69+
if errTzUtil == nil {
70+
const dstOffSuffix = "_dstoff"
71+
dstOff = strings.HasSuffix(winTZname, dstOffSuffix)
72+
return strings.TrimSuffix(winTZname, dstOffSuffix), dstOff, nil
73+
}
74+
75+
winTZname, dstOff, errReg := localTZfromReg()
76+
if errReg == nil {
77+
return winTZname, dstOff, nil
78+
}
79+
80+
return "", false, fmt.Errorf("failed to read timezone from Windows API (%v), tzutil (%v), and registry (%v)", errDynamic, errTzUtil, errReg)
81+
}
82+
7583
// localTZfromReg obtains the time zone Windows is configured to use from registry.
7684
func localTZfromReg() (string, bool, error) {
7785
k, err := registry.OpenKey(registry.LOCAL_MACHINE, tzKey, registry.QUERY_VALUE)

0 commit comments

Comments
 (0)