Go對時間操作有很好的支持。Unix紀(jì)元時間用作時間操作的參考。
我們可以使用time包中提供的Date方法來構(gòu)建時間對象。該包包含諸如year(),month(),day(),location()等方法。
我們通過使用時間對象來調(diào)用這些方法。
package main
import "fmt"
import "time"
func main() {
p := fmt.Println
present := time.Now()//當(dāng)前時間
p(present)
DOB := time.Date(1993, 02, 28, 9,04,39,213 ,time.Local)
fmt.Println(DOB)
fmt.Println(DOB.Year())
fmt.Println(DOB.Month())
fmt.Println(DOB.Day())
fmt.Println(DOB.Hour())
fmt.Println(DOB.Minute())
fmt.Println(DOB.Second())
fmt.Println(DOB.Nanosecond())
fmt.Println(DOB.Location())
fmt.Println(DOB.Weekday())
fmt.Println(DOB.Before(present))
fmt.Println(DOB.After(present))
fmt.Println(DOB.Equal(present))
diff := present.Sub(DOB)
fmt.Println(diff)
fmt.Println(diff.Hours())
fmt.Println(diff.Minutes())
fmt.Println(diff.Seconds())
fmt.Println(diff.Nanoseconds())
fmt.Println(DOB.Add(diff))
fmt.Println(DOB.Add(-diff))
}輸出:
2017-10-04 17:10:13.474931994 +0530 IST m=+0.000334969 1993-02-28 09:04:39.000000213 +0530 IST 1993 February 28 9 4 39 213 Local Sunday true false false 215624h5m34.474931781s 215624.09290970326 1.2937445574582197e+07 7.762467344749318e+08 776246734474931781 2017-10-04 17:10:13.474931994 +0530 IST 1968-07-25 00:59:04.525068432 +0530 IST Process finished with exit code 0
package main
import (
"fmt"
"time"
)
func main() {
present := time.Now()
fmt.Println("Today : ", present.Format("Mon, Jan 2, 2006 at 3:04pm"))
someTime := time.Date(2017, time.March, 30, 11, 30, 55, 123456, time.Local)
// 使用 time.Equal()比較時間
sameTime := someTime.Equal(present)
fmt.Println("someTime equals to now ? : ", sameTime)
//計(jì)算今天和以前之間的時差
diff := present.Sub(someTime)
//將差異轉(zhuǎn)換為天數(shù)
days := int(diff.Hours() / 24)
fmt.Printf("30th March 2017 was %d days ago \n", days)
}輸出:
Today : Wed, Oct 4, 2017 at 5:15pm someTime equals to now ? : false 30th March 2017 was 188 days ago