1. Problem description
Under Windows, the time zone of () and the time zone of () are the same.
However, in the Linux environment, the default time zone of () is UTC, and the default time zone of () is local. If both are not processed properly, it will lead to errors.
package main import "time" import "fmt" func main(){ t, err := ("2006-01-02 15:04:05", "2017-12-03 22:01:02") if err != nil{ (err) return } (t) (()) (().Sub(t).Seconds()) }
Output:
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 zones of the two are different and the result is not in line with expectations if the time is subtracted from the two.
2. Solution
Use() instead of():
package main import "time" import "fmt" func main(){ localTime, err := ("2006-01-02 15:04:05", "2017-12-03 22:01:02", ) if err != nil{ (err) return } (localTime) (()) (().Sub(localTime).Seconds()) }
result:
2017-12-03 22:01:02 +0800 CST
2017-12-03 22:18:26.288174547 +0800 CST m=+0.001532618
1044.288357362
Supplement: The most narcissistic golang's pit
I want to format the output date
fmt. Println (time. Now (). Format ( "2010-10-10 15:04:05" ))
The result is output
9060-60-60 11:11:36
What the hell is this
Baidu has a
fmt. Println (time. Now (). Format ( "2006-01-02 15:04:05" ))
This output is correct
2017-06-09 11:12:39
Why? No problem, because go language is the most narcissistic. It is said that date is the birth time of GO language, so you must use this date to format it.
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.