完整代码
https://github.com/smallinsect/MyGo/tree/master/mytimer
//时间转换的模板,golang里面只能是 "2006-01-02 15:04:05" (go的诞生时间) var TIME_LAYOUT string = "2006-01-02 15:04:05"
var ( testTime string = "2020-07-08 10:00:00" )
Unix()时间戳,和时区无关。
1、字符串转时间,默认UTC
fmt.Println("==================================") start, _ := time.Parse(TIME_LAYOUT, testTime) fmt.Println(start) fmt.Println(start.Unix()) fmt.Println(start.UTC()) fmt.Println(start.UTC().Unix())
2、字符串转时间,添加时区
fmt.Println("==================================") startT, _ := time.ParseInLocation(TIME_LAYOUT, "2020-03-25 18:00:00", time.Local) fmt.Println(startT) fmt.Println(startT.Unix()) fmt.Println(startT.UTC()) fmt.Println(startT.UTC().Unix())
3、Now()获取当前系统时区当前时间
fmt.Println("==================================") now := time.Now() fmt.Println(now) fmt.Println(now.Unix()) fmt.Println(now.UTC()) fmt.Println(now.UTC().Unix())
4、设置现在时间
fmt.Println("==================================") var cstSh, _ = time.LoadLocation("Asia/Shanghai") //上海 fmt.Println(now.In(cstSh)) var utcSh, _ = time.LoadLocation("UTC") fmt.Println(now.In(utcSh))
5、时区
fmt.Println("==================================") fmt.Println(time.Now().Zone()) fmt.Println(time.LoadLocation("Local")) //获取时区 timeStr := time.Now().Format("2006-01-02 15:04:05") //转化所需模板 loc, _ := time.LoadLocation("Local") //获取时区 fmt.Println(time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)) //使用模板在对应时区转化为time.time类型 fmt.Println(time.Local)
6、Unix时间转时间
fmt.Println("==================================") fmt.Println(now) fmt.Println(now.Unix()) fmt.Println(now.UTC()) fmt.Println(time.Unix(now.Unix(), 0)) // Unix()转时间,默认当地时间 fmt.Println(time.Unix(now.Unix(), 0).In(utcSh)) //Unix转时间,设置时区
7、时间转字符串
// 时间转字符串
fmt.Println("==================================")
lnow := now.Format(TIME_LAYOUT)
fmt.Println(lnow)
lnow = now.In(utcSh).Format(TIME_LAYOUT)
fmt.Println(lnow)