1. 程式人生 > 其它 >TSINGSEE青犀視訊開發中Go語言時間轉換分享

TSINGSEE青犀視訊開發中Go語言時間轉換分享

在我們開發視訊平臺智慧分析功能的過程中,系統的時間因素也是需要注意的。在很多實際業務中,需要大量處理視訊或者分析結果的時間日期時區資料。我們多用golang來進行編譯和開發,因此本文分享一下我們使用go中需要的各種日期和時間的轉換。

1、毫秒轉go time.Time型別;注意把毫秒轉成納秒,在轉成go time.Time,這樣就能取到年月日時分秒

func MsToTime(ms int64) time.Time {
	tm := time.Unix(0, ms*int64(time.Millisecond))
	//fmt.Println(tm.Format("2006-02-01 15:04:05.000"))
	return tm
}

2、毫秒轉成時間格式,如轉:2021-14-14 14:00:00格式;需要注意的是必須為這個引數(”2006-02-01 15:04:05”)

func MsToTimeStr(ms int64) string {
	t := MsToTime(ms)
	return t.Format("2006-02-01 15:04:05")
}

3、把字串日期(如:2021-14-14 14:00:00)格式轉換成毫秒:

func ParseTimeStrToTimestamp(timeStr string, flag int) int64 {
	var t int64
	loc, _ := time.LoadLocation("Local")//此處必須要,不然轉換有問題
	if flag == 1 {
		t1, _ := time.ParseInLocation("2006.01.02 15:04:05", timeStr, loc)
		t = t1.UnixNano() / 1e6
	} else if flag == 2 {
		t1, _ := time.ParseInLocation("2006-01-02 15:04", timeStr, loc)
		t = t1.UnixNano() / 1e6
	} else if flag == 3 {
		t1, _ := time.ParseInLocation("2006-01-02", timeStr, loc)
		t = t1.UnixNano() / 1e6
	} else if flag == 4 {
		t1, _ := time.ParseInLocation("2006.01.02", timeStr, loc)
		t = t1.UnixNano() / 1e6
	} else {
		t1, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
		t = t1.UnixNano() / 1e6
	}
	return t
}

4、獲取前一天的日期演算法:

//day引數為負數
func GetLastYMDH(day int) (y, m, d, h int, timestamp int64) {
	now := GetCurrentNow()
	tomorrow := now.AddDate(0, 0, day)
	//lastTime := GetCurrentMillisecond() + day * 24 * 60 * 60 * 1000
	//t := MsToTime(lastTime)
	//Y := t.Year()
	//M := t.Month()
	//D := t.Day()
	//H := t.Hour()
	Y := tomorrow.Year()
	M := tomorrow.Month()
	D := tomorrow.Day()
	H := tomorrow.Hour()
	timestamp = tomorrow.UnixNano() / 1e6 //轉毫秒
	return Y, int(M), D, H, timestamp
}