📅  最后修改于: 2021-01-02 09:10:34             🧑  作者: Mango
Go对时间操作有很好的支持。 Unix纪元时间用作时间操纵的参考。
我们可以使用时间包中提供的Date方法来构建时间对象。该软件包包含诸如year(),month(),day(),location()等方法。
我们通过使用时间对象来调用这些方法。
package main
import "fmt"
import "time"
func main() {
p := fmt.Println
present := time.Now()// current time
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)
// compare time with time.Equal()
sameTime := someTime.Equal(present)
fmt.Println("someTime equals to now ? : ", sameTime)
// calculate the time different between today
// and long time ago
diff := present.Sub(someTime)
// convert diff to days
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