This is a creation in Article, where the information may have evolved or changed.
Time zone issues for Time.parse and Time.format in Golang
posted in 2017-12-03
| classified in coding
First, the problem description
windowsunder, time.Parse() the time zone and time.Format() the time zone are consistent.
However, in an environment where the linux time.Parse() default time zone is UTC , time.Format() the time zone defaults to local, and the two will cause an error if not handled properly.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
Package main Import "Time" import "FMT" func main(){ T, err: = time. Parse ("2006-01-02 15:04:05", "2017-12-03 22:01:02") if err! = Nil{ FMT. PRINTLN (ERR) return } FMT. Println (t) FMT. Println (time. Now ()) FMT. Println (time. Now (). Sub (t). Seconds ()) }
|
Output:
1 2 3
|
2017-12-03 22:01:02 +0000 UTC 2017-12-03 22:15:26.592204446 +0800 CST m=+0.003020091 -27935.407549533
|
It is obvious that the time zone between the two is different and that if you subtract the time, the results do not meet the expectations.
Second, the solution
Use time.ParseInLocation() instead of time.Parse() :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
Package main
Import "Time" import "FMT"
func main(){ localtime, err: = time. Parseinlocation ("2006-01-02 15:04:05", "2017-12-03 22:01:02", time. Local) if err! = Nil{ FMT. PRINTLN (ERR) return } FMT. Println (localtime) FMT. Println (time. Now ()) FMT. Println (time. Now (). Sub (localtime). Seconds ()) }
|
Results:
1 2 3
|
2017-12-03 22:01:02 +0800 CST 2017-12-03 22:18:26.288174547 +0800 CST m=+0.001532618 1044.288357362
|
Golang Redis Small Case (ii): REDIS Implementation Message Queuing Redis Learning notes: Subscribing and publishing
- Article Directory
- Site Overview
Ma Yi Ma Yi Ma Yi
It's a long way to mend
291 log classification
Links
- First, the problem description
- Second, the solution