English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Go has good support for time operations. Unix epoch time is used as the reference for time operations.
We can use the Date method provided by the time package to build time objects. The package includes methods such as year(), month(), day(), location(), and so on.
We can call these methods by using time objects.
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) // 使用 time.Equal()比较时间 sameTime := someTime.Equal(present) fmt.Println("someTime equals to now ? : ", sameTime) //计算今天和以前之间的时差 diff := present.Sub(someTime) //将差异转换为天数 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