将CST日期时间转换为Golang中的Unix时间戳。

huangapple go评论71阅读模式
英文:

Convert CST DateTime to Unix timestamp in Golang

问题

我有一个中国标准时间的日期时间格式为0000-00-00 00:00:00,我想将其转换为Golang中的Unix时间戳。

如果我们直接调用time.Unix(),我不确定我们需要哪种默认时间戳。

英文:

I have a datetime format 0000-00-00 00:00:00 in China Standard Time, I want to convert it to unix timestamp in Golang.

I am not sure what default timestamp we need, if we call time.Unix( ) directly.

答案1

得分: 2

只需使用time.Location即可。

func main() {
	now := "2022-08-11 11:40:00"
	location, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		log.Fatalln(err)
	}
	t, err := time.ParseInLocation("2006-01-02 15:04:05", now, location)
	if err != nil {
		log.Fatalln(err)
	}
	//2022-08-11 11:40:00 +0800 CST
	fmt.Println(t)
	//1660189200
	fmt.Println(t.Unix())
}
英文:

just use time.Location

func main() {
	now := "2022-08-11 11:40:00"
	location, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		log.Fatalln(err)
	}
	t, err := time.ParseInLocation("2006-01-02 15:04:05", now, location)
	if err != nil {
		log.Fatalln(err)
	}
	//2022-08-11 11:40:00 +0800 CST
	fmt.Println(t)
	//1660189200
	fmt.Println(t.Unix())
}

huangapple
  • 本文由 发表于 2022年8月11日 08:18:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73314013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定