时间初始化
除了最常用的time.Now,go还提供了通过unix标准时间、字符串两种方式来初始化:
//通过字符串,默认UTC时区初始化Time
func Parse(layout, value string) (Time, error)
//通过字符串,指定时区来初始化Time
func ParseInLocation(layout, value string, loc *Location) (Time, error)
//通过unix 标准时间初始化Time
func Unix(sec int64, nsec int64) Time
时间初始化的时候,一定要注意原始输入值的时区。正好手里有一个变量,洛杉矶当地时间“2016-11-28 19:36:25”,unix时间精确到秒为1480390585。将其解析出来的代码如下:
local, _ := time.LoadLocation("America/Los_Angeles")
timeFormat := "2006-01-02 15:04:05"
//func Unix(sec int64, nsec int64) Time {
time1 := time.Unix(1480390585, 0) //通过unix标准时间的秒,纳秒设置时间
time2, _ := time.ParseInLocation(timeFormat, "2016-11-28 19:36:25", local) //洛杉矶时间
fmt.Println(time1.In(local).Format(timeFormat))
fmt.Println(time2.In(local).Format(timeFormat))
chinaLocal, _ := time.LoadLocation("Local")//运行时,该服务器必须设置为中国时区,否则最好是采用"Asia/Chongqing"之类具体的参数。
fmt.Println(time2.In(chinaLocal).Format(timeFormat))
//output:
//2016-11-28 19:36:25
//2016-11-28 19:36:25
//2016-11-29 11:36:25
当然,如果输入值是字符串,且带有时区
“2016-12-04 15:39:06 +0800 CST”
则不需要采用ParseInLocation方法,直接使用Parse即可。
当然,其他time包中的函数还有很多,但网上已经有很多描述,就不再啰嗦。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。









