Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting string like "2021-05-06 00:00:00 +0530 IST" to time.Time value in golang

I have the following string 2021-05-06 00:00:00 +0530 IST that I need to convert to a time.Time value in golang. I know how to do it but I don’t know what the layout should be to parse these type of strings.

time, err := time.ParseInLocation("2021-05-06 00:00:00 +0530 IST", addedOn, loc)

And this is giving me errors like "error":"parsing time \"2021-05-06 00:00:00 +0530 IST\" as \"2021-05-06 00:00:00 +0530 IST\": cannot parse \"-05-06 00:00:00 +0530 IST\" as \"1\""

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, what should be the correct layout for such strings?

>Solution :

You are putting the date in place of the time layout.

See time#ParseInLocation

func ParseInLocation(layout, value string, loc *Location) (Time, error)

For instance:

loc, _ := time.LoadLocation("Europe/Berlin")

// This will look for the name CEST in the Europe/Berlin time zone.
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
fmt.Println(t)

In your case:

t , _ := time.ParseInLocation("2006-01-02 15:04:05 -0700 MST", "2021-05-06 00:00:00 +0530 IST", loc)

See playground example (and other ParseInLocation examples here)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading