如何将UTC时间转换为Unix时间戳

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

How to convert UTC time to unix timestamp

问题

我正在寻找一种将UTC时间字符串转换为Unix时间戳的方法。

我有一个字符串变量 02/28/2016 10:03:46 PM,需要将其转换为类似于 1456693426 的Unix时间戳。

你有任何想法如何实现吗?

英文:

I am looking for an option to convert UTC time string to unix timestamp.

The string variable I have is 02/28/2016 10:03:46 PM and it needs to be converted to a unix timestamp like 1456693426

Any idea how to do that?

答案1

得分: 19

首先,Unix时间戳1456693426在UTC时间中并不是10:03:46 PM,而是9:03:46 PM

time包中,有一个名为Parse的函数,它需要一个布局参数来解析时间。布局参数是根据参考时间Mon Jan 2 15:04:05 -0700 MST 2006构建的。所以在你的情况下,布局参数应该是01/02/2006 3:04:05 PM。使用Parse函数后,你会得到一个time.Time结构体,你可以调用Unix方法来获取Unix时间戳。

package main

import (
	"fmt"
	"time"
)

func main() {
	layout := "01/02/2006 3:04:05 PM"
	t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t.Unix())
}
英文:

First of, the unix timestamp 1456693426 does not have the time 10:03:46 PM but 9:03:46 PM in UTC.

In the time package there is the function Parse with expects a layout to parse the time. The layout is constructed from the reference time Mon Jan 2 15:04:05 -0700 MST 2006. So in your case the layout would be 01/02/2006 3:04:05 PM. After using Parse you get a time.Time struct on which you can call Unix to receive the unix timestamp.

package main

import (
	"fmt"
	"time"
)

func main() {
	layout := "01/02/2006 3:04:05 PM"
	t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t.Unix())
}

huangapple
  • 本文由 发表于 2016年2月29日 05:20:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/35688419.html
匿名

发表评论

匿名网友

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

确定