In Go, while trying to convert string to time.Time
, using time package's Parse method doesn't return expected result. It seems problem is with the timezone. I want to change to ISO 8601 combined with date and time in UTC.
package main
import (
"fmt"
"time"
)
func main() {
const longForm = "2013-05-13T18:41:34.848Z"
//even this is not working
//const longForm = "2013-05-13 18:41:34.848 -0700 PDT"
t, _ := time.Parse(longForm, "2013-05-13 18:41:34.848 -0700 PDT")
fmt.Println(t)
//outputs 0001-01-01 00:00:00 +0000 UTC
}
thanks in advance!
time.Parse
uses special values for time formatting, and expecting the format to be passed with those values.
If you pass correct values, it will parse the time in the correct manner.
So passing year as 2006, month as 01 and goes on like that...
package main
import (
"fmt"
"time"
)
func main() {
const longForm = "2006-01-02 15:04:05.000 -0700 PDT"
t, err := time.Parse(longForm, "2013-05-13 18:41:34.848 -0700 PDT")
fmt.Println(t.UTC(), err)
//outputs 2013-05-14 01:41:34.848 +0000 UTC <nil>
}
Your format string longForm
is not correct. You would know that if you would have not been ignoring the returned error. Quoting the docs:
These are predefined layouts for use in Time.Format and Time.Parse. The reference time used in the layouts is:
Mon Jan 2 15:04:05 MST 2006
which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as
01/02 03:04:05PM '06 -0700
To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples.
package main
import (
"fmt"
"log"
"time"
)
func main() {
const longForm = "2006-01-02 15:04:05 -0700"
t, err := time.Parse(longForm, "2013-05-13 18:41:34.848 -0700")
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
}
Output:
2013-05-13 01:41:34.848 +0000 UTC