Go’s offers extensive support for times and durations; More examples: http://golang.org/pkg/time/#pkg-examples |
|
package main
|
|
import "fmt"
import "time"
|
|
func main() {
p := fmt.Println
|
|
We’ll start by getting the current time. |
now := time.Now()
p(now)
|
You can build a |
then := time.Date(
2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
p(then)
|
You can extract the various components of the time value as expected. |
p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location())
|
The Monday-Sunday |
p(then.Weekday())
|
These methods compare two times, testing if the first occurs before, after, or at the same time as the second, respectively. |
p(then.Before(now))
p(then.After(now))
p(then.Equal(now))
|
The |
diff := now.Sub(then)
p(diff)
|
We can compute the length of the duration in various units. |
p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
p(diff.Nanoseconds())
|
You can use |
p(then.Add(diff))
p(then.Add(-diff))
|
Use constants like: Nanosecond, Microsecond, Millisecond, Second, Minute, Hour to get new time, like this example to print date after/before 30 days. Note: Substract one month is not equal to 30 days. |
p(now.Add(30 * 24 * time.Hour).Format("2006-01-02"))
p(now.Add(-30 * 24 * time.Hour).Format("2006-01-02"))
p(now.AddDate(0, -1, 0).Format("2006-01-02"))
p(now.AddDate(0, 0, -30).Format("2006-01-02"))
}
|
$ go run time.go
2014-09-09 17:17:15.474872708 +0800 CST
2009-11-17 20:34:58.651387237 +0000 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
42156h42m16.823485471s
42156.70467319041
2.5294022803914244e+06
1.5176413682348546e+08
151764136823485471
2014-09-09 09:17:15.474872708 +0000 UTC
2005-01-26 07:52:41.827901766 +0000 UTC
2014-10-09
2014-08-10
2014-08-09
2014-08-10
|
Previous example: JSON.
Next example: Epoch.