如何将' 2022-11-20 21:00:00+0900 '格式化为IST



我有一个时间戳2022-11-20 21:00:00+0900,现在我需要将其转换为IST。所以我尝试了

loc, _ := time.LoadLocation("Asia/Calcutta")
format := "Jan _2 2006 3:04:05 PM"
timestamp := "2022-11-20 21:00:00+0900"
ISTformat, err := time.ParseInLocation(format, timestamp,  loc)
fmt.Println(ISTformat, err)

,但没有工作,并给出错误cannot parse

我需要使用什么类型的golang时间格式来完成此操作?

试试下面的

loc, _ := time.LoadLocation("Asia/Calcutta")
format := "2006-01-02 15:04:05-0700"
timestamp := "2022-11-20 21:00:00+0900"
// ISTformat, _ := time.ParseInLocation(format, timestamp, loc)
// fmt.Println(ISTformat)
parsed_time, _ := time.Parse(format, timestamp)
IST_time := parsed_time.In(loc)
fmt.Println("Time in IST", IST_time)

注意你的formattimestamp应该在相同的时间格式

ParseInLocation与Parse类似,但在两个重要方面有所不同。首先,在没有时区信息的情况下,Parse将时间解释为UTC;ParseInLocation将时间解释为给定位置中的时间。其次,当给定一个区域偏移量或缩写时,Parse会尝试将其与Local位置进行匹配;ParseInLocation使用给定的位置。

** ParseInLocation格式为**函数ParseInLocation(布局,值字符串,loc *位置)(时间,错误)

你试试这个例子

package main
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("Asia/Calcutta")
// This will look for the name CEST in the Asia/Calcutta 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)
// Note: without explicit zone, returns time in given location.
const shortForm = "2006-Jan-02"
t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
fmt.Println(t)
return
}

有关更多信息,您可以阅读GO lang time包中的time文档这是链接https://pkg.go.dev/time#Date

相关内容

最新更新