Home > database >  Parse nodeJs Date.toString() output as time in go
Parse nodeJs Date.toString() output as time in go

Time:12-02

I have a go service which receives data from an external service.

The data looks as follows (json)-

{
  "firstName": "XYZ",
  "lastName": "ABC",
  "createdAtTimestamp": "Mon Nov 21 2022 17:01:59 GMT 0530 (India Standard Time)"
}

Note that createdAtTimestamp is the output in format of nodeJS new Date().toString() which does not have any particular RFC format specified.

How do I parse createdAtTimestamp to time in go ?

I tried this but it is failing-

data, _ := time.Parse(time.RFC1123, "Mon Nov 21 2022 17:01:59 GMT 0530 (India Standard Time)")
    fmt.Println(data.Format(time.RFC3339))

CodePudding user response:

You can use below Layout to parse your date:

"Mon Jan 02 2006 15:04:05 MST-0700"

In the lines of:

date := "Mon Nov 21 2022 17:01:59 GMT 0530 (India Standard Time)"
data, err := time.Parse("Mon Jan 02 2006 15:04:05 MST-0700", strings.Split(date, " (")[0])

CodePudding user response:

I think you'll have to strip off (India Standard Time) (unless you know it will be the same each time), but you can do

https://go.dev/play/p/rWqO9W3laM2

str := "Mon Nov 21 2022 17:01:59 GMT 0530 (India Standard Time)"
data, err := time.Parse("Mon Jan 02 2006 15:04:05 MST-0700", str[:strings.Index(str, " (")])
fmt.Println(data.Format(time.RFC3339), err)

or, if it will always have (India Standard Time), you could do:

str := "Mon Nov 21 2022 17:01:59 GMT 0530 (India Standard Time)"
data, err := time.Parse("Mon Jan 02 2006 15:04:05 MST-0700 (India Standard Time)", str)
fmt.Println(data.Format(time.RFC3339), err)
  • Related