go语言time用法总结

1. time.Unix()函数返回公元1970年1月,1日,0时,0分,0秒以来的秒数

代码示例1:

// UTC时间1970年1月1日0时0分45秒,所以会打印出 t:45
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "1970-01-01 00:00:45", time.UTC)
fmt.Println("t:", t.Unix())
结果如下图:

 

 

 

代码示例2:

// 本地时间1970年1月1日8时0分50秒,因为是中国时间是东八区,比UTC时间早8个小时
// 相当于UTC的"1970-01-01 08:00:50",所以会打印出 t:50
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "1970-01-01 08:00:50", time.Local)
fmt.Println("t:", t.Unix())
结果如下图:

 

 

 

2. time.Time()声明时,若未初始化则表示UTC时间,公元1年,1月,1日,0时,0分,0秒

代码示例:

t1 := time.Time{}
t2 := time.Now()
t1Second := t1.Unix()
t2Second := t2.Unix()
fmt.Printf("t1:%v, t1Second:%v \n", t1, t1Second) // UTC时间1970-01-01 08:00:50的秒数为0,所以在此时间之前的为负值,且在int32范围之外
fmt.Printf("t2:%v, t2Second:%v \n", t2, t2Second)
fmt.Println("t2Second-t1Second=", t2Second-t1Second) // 所以会返回一个超大的值,已超过int32范围
结果如下图:

 

 

 

3. 秒数转Duration,例如 dur := 2*time.Second + 500*time.Millisecond

代码示例:

t1 := time.Now() // 当前时间
time.Sleep(3 * time.Second) // 休眠3秒
dur := 2*time.Second + 500*time.Millisecond // 规定间隔:2秒500毫秒
// 判断间隔时间
if time.Now().Sub(t1) > dur {
fmt.Println("sleep over 2.5s")
}
结果如下图:

 

 

 

4. time.Duration 转秒数,接示例3:durSec := dur.Seconds(),返回值类型为float64类型

代码示例:

dur := 2*time.Second + 500*time.Millisecond
durSec := dur.Seconds()
fmt.Println("durSec:", durSec)
结果如下图:

 

 

 

5. 时间字符串转为本地时间,比如 "2019-03-18 16:31:45"转为本地时间或UTC时间

代码示例:

// 解析字符串 "2019-06-18 08:47:50"为本地时间
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2019-06-18 08:47:50", time.Local)
fmt.Println("t:", t)
结果如下图:

 

 

 

6. 比较两个时间Time是否相等

代码示例:

// 解析字符串 "2019-06-18 08:47:50"为本地时间
t1, _ := time.ParseInLocation("2006-01-02 15:04:05", "2019-06-18 08:47:50", time.Local)
t2, _ := time.ParseInLocation("2006-01-02 15:04:05", "2019-06-18 08:47:50", time.Local)
if t1.Equal(t2) {
fmt.Println("t1 == t2")
}
结果如下图:

 

 

 

7. 得到当年,当月,当日,0时,0分,0秒的时间字符串

代码示例:

t1 := time.Now() // 2019年6月18日
curDayStr := t1.Format("2006-01-02 00:00:00") // 固定到天
curMonthStr := t1.Format("2006-01-00 00:00:00") // 固定到月
fmt.Printf("curDayStr:%v \n", curDayStr)
fmt.Printf("curMonthStr:%v \n", curMonthStr)
结果如下图:

 

posted on 2021-03-28 12:33  Code2020  阅读(1222)  评论(0编辑  收藏  举报