Why is time.Parse
not using timezone information? It should return different time for different timezones.
Code
package main
import (
"fmt"
"time"
)
func main() {
t, err := time.Parse("2006-01-02 MST", "2018-05-11 IST")
if err != nil {
return
}
t2, err := time.Parse("2006-01-02 MST", "2018-05-11 UTC")
if err != nil {
return
}
fmt.Println(t.Unix())
fmt.Println(t2.Unix())
}
Output:
1525996800
1525996800
Some explanation to the question itself:
These 2 timestamps
2018-05-11 IST
and2018-05-11 UTC
do not designate the same time instant because IST has a different offset than UTC: India Standard Time (IST) is 5:30 hours ahead of Coordinated Universal Time (UTC).And
Time.Unix()
returns the elapsed seconds up to the time instant, elapsed since the reference time (January 1, 1970 UTC). Which implies the output should be different!Running your code on the PlayGround indeed gives wrong result (link).
And it is a timezone related issue. If you try to load the IST timezone:
Output:
And the reason why "IST" is not supported is because it is ambiguous. It could mean India, Ireland, Israel, etc. time zones, which have different zone offsets and rules.
And documentation of
time.Parse()
states thatSo the
time.time
returned byparse.Parse()
will have 0 offset just like the UTC zone, hence it will result in the same "unix time" (Time.Unix()
will return the same value).But running it locally (with my CET) timezone gives different, correct result:
Output:
Documentation of
time.Parse()
has this to say about parsing a time with zone abbreviation:Documentation suggests to parse with a layout with numeric zone offset, like this:
Then output (try it on the Go Playground):
Another option is to use
time.FixedZone()
to constructIST
yourself, and usetime.ParseInLocation()
, passing our manualIST
location:Output will be (try it on the Go Playground):