返回本地的一天开始时间对象 [英] Return local beginning of day time object

查看:55
本文介绍了返回本地的一天开始时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要获取今天时间对象的本地开始时间,我提取YMD并重建新日期。看起来像是在跳动。我还会错过其他一些标准库函数吗?

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?

代码也可以在 http://play.golang.org/p/OSRl0nxyB7

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 main() {
    fmt.Println(Bod(time.Now()))
}


推荐答案

问题的标题和文本都要求本地[芝加哥]开头今天时间。问题中的 Bod 函数正确地做到了这一点。 接受 Truncate 函数声称是更好的解决方案,但返回的结果不同;它不会在今天开始返回本地[芝加哥]。例如,

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))
}

输出:

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

时间截断方法会截断UTC时间。

The time.Truncate method truncates UTC time.

接受的截断函数还假定一天中有24小时。芝加哥一天有23、24或25个小时。

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

这篇关于返回本地的一天开始时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆