0

I tried parsing

Tue Apr 07 2020 11:17:47 GMT+0530 (India Standard Time)

But got the following error

parsing time "Tue Apr 07 2020 11:17:47 GMT+0530 (India Standard Time)" as "2006-01-02T15:04:05Z07:00": cannot parse "Tue Apr 07 2020 11:17:47 GMT+0530 (India Standard Time)" as "2006" 0001-01-01 00:00:00 +0000 UTC

From the frontend i can get timestamp in any format depending on the location or zone.But, in go lang i'm trying to parse any timestamp and convert it to UTC to store in ledger.What is the correct way to handle this case?

t, err := time.Parse(time.RFC3339, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)
1
  • You should use different layout instead of time.RFC3339. time.RFC3339 is for dates like 2006-01-02T15:04:05Z Commented Apr 7, 2020 at 6:17

1 Answer 1

2

The reference time used in the Go time layouts is the specific time, Mon Jan 2 15:04:05 MST 2006. To define your own format, write down what the reference time would look like formatted your way.

Since MST is GMT-0700, use your ref string that way in the first argument.

package main

import (
    "fmt"
    "time"
)

func main() {

    // Parsing your custom time format by using the reference time in your format.
    t1, err := time.Parse(
             "Mon Jan 02 2006 15:04:05 GMT-0700",
             "Tue Apr 07 2020 11:17:47 GMT+0530")

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(t1.UTC())
}

The Go Playground

Sign up to request clarification or add additional context in comments.

4 Comments

But my question is what to do when i don't know in which format i'm going to get the date and i also want to store all timestamp in UTC format
@alia: I'm afraid that's not possible, how would you expect the runtime to identify the type without providing it a reference string?
@alia: Updated to have the result in UTC
@alia, you have to call time.Parse multiple times, once for each supported format, and see which one doesn't return an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.