Return local beginning of day time object

后端 未结 2 442
天命终不由人
天命终不由人 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:14

    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.

提交回复
热议问题