...
1## Get the full name of your local time zone (OS setting)
2
3Works on windows, linux and macos
4
5### Why?
6built-in functionality sometimes won't suffice:
7```go
8 zone, _ := time.Now().Zone() // try to get my time zone...
9 loc, _ := time.LoadLocation(zone)
10 fmt.Println(zone, loc) // prints e.g. CEST UTC -> obviously wrong!
11```
12localizing a date with obtained `loc` will cause
13> panic: time: missing Location in call to Date
14
15---
16
17### Package Usage
18```
19go get github.com/thlib/go-timezone-local/tzlocal
20```
21
22### See it in action:
23
24Open your project folder
25Create a file `main.go`
26
27```go
28package main
29
30import (
31 "fmt"
32 "time"
33
34 "github.com/thlib/go-timezone-local/tzlocal"
35)
36
37func main() {
38 tzname, err := tzlocal.RuntimeTZ()
39 fmt.Println(tzname, err)
40
41 // example:
42 // tzname = "Europe/Berlin"
43
44 // now you can use tzname to properly set up a location:
45 loc, _ := time.LoadLocation(tzname)
46
47 d0 := time.Date(2021, 10, 30, 20, 0, 0, 0, loc) // DST active:
48 fmt.Println(d0)
49 // 2021-10-30 20:00:00 +0200 CEST
50
51 d1 := d0.AddDate(0, 0, 1) // add one day, now DST is inactive:
52 fmt.Println(d1)
53 // 2021-10-31 20:00:00 +0100 CET
54}
55```
56
57Run the following commands:
58```
59go mod init example.com/yourpackage
60go mod vendor
61go run main.go
62```
63
64It should print the go runtime timezone.
65
66
67### For contributors to update the list of time zones on windows
68
69Clone github.com/thlib/go-timezone-local
70Change directory to go-timezone-local
71
72```
73cd go-timezone-local
74go generate ./...
75```
76
77### Credits
78
79All credit goes to [colm.anseo](https://stackoverflow.com/users/1218512/colm-anseo) and [MrFuppes](https://stackoverflow.com/users/10197418/mrfuppes) for providing the following answers:
80* https://stackoverflow.com/a/68938947/175071
81* https://stackoverflow.com/a/68966317/175071
View as plain text