【问题标题】:Parse nodeJs Date.toString() output as time in goParse nodeJs Date.toString() output as time in go
【发布时间】:2022-12-02 03:11:49
【问题描述】:
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))
【问题讨论】:
标签:
javascript
node.js
go
【解决方案1】:
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)