1. 程式人生 > >GoLang 獲取兩個時間相差多少小時

GoLang 獲取兩個時間相差多少小時

程式碼如下

如果呼叫 time .parse() 這個玩意相差 8小時。預設時區是utc 

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(getHourDiffer("2016-09-10 13:00:00", "2016-09-10 14:50:00"))
}

//獲取相差時間
func getHourDiffer(start_time, end_time string) int64 {
	var hour int64
	t1, err := time.ParseInLocation("2006-01-02 15:04:05", start_time, time.Local)
	t2, err := time.ParseInLocation("2006-01-02 15:04:05", end_time, time.Local)
	if err == nil && t1.Before(t2) {
		diff := t2.Unix() - t1.Unix() //
		hour = diff / 3600
		return hour
	} else {
		return hour
	}
}