Return local beginning of day time object in Go

Both the title and the text of the question asked for "a local [Chicago] beginning of today time." The Bod function in the question did that correctly. The accepted Truncate function claims to be a better solution, but it returns a different result; it doesn't return a local [Chicago] beginning of today time. For example,

package main

import ( "fmt" "time" ) func Bod(t time.Time) time.Time { year, month, day := t.Date() return time.Date(year, month, day, 0, 0, 0, 0, t.Location()) } func Truncate(t time.Time) time.Time { return t.Truncate(24 * time.Hour) } func main() { chicago, err := time.LoadLocation("America/Chicago") if err != nil { fmt.Println(err) return } now := time.Now().In(chicago) fmt.Println(Bod(now)) fmt.Println(Truncate(now)) }

Output:

2014-08-11 00:00:00 -0400 EDT 2014-08-11 20:00:00 -0400 EDT

The time.Truncate method truncates UTC time.

The accepted Truncate function also assumes that there are 24 hours in a day. Chicago has 23, 24, or 25 hours in a day.

转载于:https://www.cnblogs.com/oxspirt/p/11401098.html

你可能感兴趣的:(Return local beginning of day time object in Go)