Return local beginning of day time object

后端 未结 2 427
天命终不由人
天命终不由人 2020-12-30 22:48

To get a local beginning of today time object I extract YMD and reconstruct the new date. That looks like a kludge. Do I miss some other standard library function?

c

2条回答
  •  醉梦人生
    2020-12-30 23:10

    EDIT: This only works for UTC times (it was tested in the playground, so the location-specific test was probably wrong). See PeterSO's answer for issues of this solution in location-specific scenarios.

    You can use the Truncate method on the date, with 24 * time.Hour as duration:

    http://play.golang.org/p/zJ8s9-6Pck

    func main() {
        // Test with a location works fine too
        loc, _ := time.LoadLocation("Europe/Berlin")
        t1, _ := time.ParseInLocation("2006 Jan 02 15:04:05 (MST)", "2012 Dec 07 03:15:30 (CEST)", loc)
        t2, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 00:00:00")
        t3, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 23:15:30")
        t4, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 23:59:59")
        t5, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 08 00:00:01")
        times := []time.Time{t1, t2, t3, t4, t5}
    
        for _, d := range times {
            fmt.Printf("%s\n", d.Truncate(24*time.Hour))
        }
    }
    

    To add some explanation, it works because truncate "rounds down to a multiple of" the specified duration since the zero time, and the zero time is January 1, year 1, 00:00:00. So truncating to the nearest 24-hour boundary always returns a "beginning of day".

提交回复
热议问题