Date to string
// 格式化
// golang中格式不是‘yyyy-MM-dd HH:mm:ss’,而是采用golang诞生时间作为格式
t = "2006-01-02 15:04:05"
time := time.Now()
fmt.Println(time.Format(t))
Detailed link: https://www.jianshu.com/p/d853d1d42076
String to date
Golang uses UTC by default, which is Unix standard time. In general, we use the Chinese time for storing the database, that is, CST.
UTC and CST generally differ by 8 hours.
time := time.Now()
// 默认UTC
loc, err := time.LoadLocation("")
// 一般为CST
loc, err := time.LoadLocation("Local")
// 美国洛杉矶PDT
loc, err := time.LoadLocation("America/Los_Angeles")
// CST
loc, _:= time.LoadLocation("Asia/Chongqing")
Convert the string type directly to the corresponding time zone time
loc, err := time.LoadLocation("Local")
dt, err := time.ParseInLocation("2006-01-02 15:04:05", "2017-05-11 14:06:06", loc)
Original link: https://blog.csdn.net/hehexiaoxia/article/details/71629225
Time zone error
Error 1
panic: time: missing Location in call to Time.In
surroundings
1. docker empty image (or similar environment)
2. loc, _ := time.LoadLocation("Asia/Chongqing") is used in Go application
the reason
The time location information is extracted from the local file system. Most systems support it, but it still depends on the current system. Specific configuration storage path:
$ cd /usr/share/zoneinfo
Enter the directory and you can see the configuration information of each time zone
$ ls
+VERSION Australia EET Factory Greenwich Jamaica Mexico Poland US posixrules
Africa Brazil EST GB HST Japan NZ Portugal UTC zone.tab
America CET EST5EDT GB-Eire Hongkong Kwajalein NZ-CHAT ROC Universal
Antarctica CST6CDT Egypt GMT Iceland Libya Navajo ROK W-SU
Arctic Canada Eire GMT+0 Indian MET PRC Singapore WET
Asia Chile Etc GMT-0 Iran MST PST8PDT Turkey Zulu
Atlantic Cuba Europe GMT0 Israel MST7MDT Pacific UCT iso3166.tab
However, these time zone configuration files do not exist in empty mirrors (or similar scenarios), and this error will appear when the program is referenced (to be precise, this problem occurs because there is no Asia/Chongqing time zone configuration file in the local system)
solve
installation
$ apk add --no-cache tzdata
After installing this package, the configuration information for each time zone will be generated in the /usr/share/zoneinfo directory. Note that if there is no timezone and locatime configuration, you need to manually handle it
Error 2
panic: time: missing Location in call to Date
This problem usually occurs when time.LoadLocation is used, which relies on the IANA Time Zone Database (tzdata for short), which is usually included in Linux systems, but not in some windows systems.
Use os.Setenv("ZONEINFO",'xx/xx/data.zip') before referencing the LoadLocation method
// rootPath is the workdir or some absolute path
os.Setenv("ZONEINFO", 'xx/xx/data.zip')
l, _ := time.LoadLocation("Asia/Shanghai")
fmt.Println(time.Now().In(l)) // 2019-05-17 15:57:43.0785088 +0800 CST
The data.zip file can be found on github: https://github.com/lesroad/tzdata