Skip to content

Commit e1ced32

Browse files
committed
time: show how to get midnight on the current day
A common task is trying to get today's date in the local time zone with zero values for the hour, minute, second, and nanosecond fields. I tried this recently and incorrectly used Truncate(24*time.Hour), which truncates based on a UTC clock, and gave me 5pm Pacific time instead of midnight Pacific. I thought it would be helpful to show a "correct" way to do this. Change-Id: I479e6b0cc56367068530981ca69882b34febf945 Reviewed-on: https://go-review.googlesource.com/46833 Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 4e9c86a commit e1ced32

File tree

1 file changed

+3
-0
lines changed

1 file changed

+3
-0
lines changed

src/time/example_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,9 @@ func ExampleTime_Truncate() {
256256
for _, d := range trunc {
257257
fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
258258
}
259+
// To round to the last midnight in the local timezone, create a new Date.
260+
midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
261+
_ = midnight
259262

260263
// Output:
261264
// t.Truncate( 1ns) = 12:15:30.918273645

0 commit comments

Comments
 (0)