Go語言編寫規範之time包
阿新 • • 發佈:2020-10-28
1.time.Time和time.Duration
time.Time可以理解為時間單位,其中包含了一些對時間的處理方法,time.Now()返回就是time.Time型別
在處理時間的瞬時時使用time.Time,在比較、新增或減去時間時使用time.Time中的方法。
Bad | Good |
func isActive(now, start, stop int) bool { return start <= now && now < stop } |
func isActive(now, start, stop time.Time) bool { |
time.Duration表示時間段,處理時間段時可以用這個方法
Bad | Good |
func poll(delay int) { for { // ... time.Sleep(time.Duration(delay) * time.Millisecond) } } poll(10) // 是幾秒鐘還是幾毫秒? |
func poll(delay time.Duration) { for |
2.獲取某些特定時間點的時間
獲取將來或者過去某個時間段的時間
tomorrow := time.Now().AddDate(0 /* years */, 0, /* months */, 1 /* days */) yesterday := time.Now().Add(-24 * time.Hour)
獲取0點時間
timeStr := time.Now().Format("2006-01-02") t, _ := time.ParseInLocation("2006-01-02", timeStr, time.Local)
3.時間的格式化
timeStr := time.Now().Format("2006-01-02") timeStr := time.Now().Format("2006-01-02 15:04:05")
4.時區選擇
func get_date_today_china() (date string, err error) { var cstZone = time.FixedZone("CST", 60*60*8)//東八區 date = time.Now().In(cstZone).Format("2006-01-02") return }