[英]time.Time Round to Day
I have a timestamp coming in, I wonder if there's a way to round it down to the start of a day in PST.我有一个时间戳进来,我想知道是否有办法将它舍入到 PST 一天的开始。 For example, ts:
1305861602
corresponds to 2016-04-14, 21:10:27 -0700
, but I want to round it to a timestamp that maps to 2016-04-14 00:00:00 -0700
.例如, ts:
1305861602
对应于2016-04-14, 21:10:27 -0700
,但我想将其四舍五入为映射到2016-04-14 00:00:00 -0700
的时间戳。 I read through the time.Time doc but didn't find a way to do it.我通读了 time.Time 文档,但没有找到办法。
The simple way to do this is to create new Time
using the previous one and only assigning the year month and day.执行此操作的简单方法是使用前一个
Time
创建新Time
,并仅分配年月和日。 It would look like this;它看起来像这样;
rounded := time.Date(toRound.Year(), toRound.Month(), toRound.Day(), 0, 0, 0, 0, toRound.Location())
here's a play example;这是一个播放示例; https://play.golang.org/p/jnFuZxruKm
https://play.golang.org/p/jnFuZxruKm
You can simply use duration 24 * time.Hour
to truncate time.您可以简单地使用持续时间
24 * time.Hour
来截断时间。
t := time.Date(2015, 4, 2, 0, 15, 30, 918273645, time.UTC)
d := 24 * time.Hour
t.Truncate(d)
https://play.golang.org/p/BTz7wjLTWX https://play.golang.org/p/BTz7wjLTWX
I believe the simplest is to create a new date as shown in this answer .我相信最简单的方法是创建一个新日期,如本答案所示。 However, if you wanna use time.Truncate, there is two distinct cases.
但是,如果您想使用 time.Truncate,则有两种不同的情况。
var testUtcTime = time.Date(2016, 4, 14, 21, 10, 27, 0, time.UTC)
// outputs 2016-04-14T00:00:00Z
fmt.Println(testUtcTime.Truncate(time.Hour * 24).Format(time.RFC3339))
var testTime = time.Date(2016, 4, 14, 21, 10, 27, 0, time.FixedZone("my zone", -7*3600))
// this is wrong (outputs 2016-04-14T17:00:00-07:00)
fmt.Println(testTime.Truncate(time.Hour * 24).Format(time.RFC3339))
// this is correct (outputs 2016-04-14T00:00:00-07:00)
fmt.Println(testTime.Add(-7 * 3600 * time.Second).Truncate(time.Hour * 24).Add(7 * 3600 * time.Second).Format(time.RFC3339))
in addition to sticky's answer to get the local Truncate
do like this除了粘性的答案以获得本地
Truncate
还可以这样做
t := time.Date(2015, 4, 2, 0, 15, 30, 918273645, time.Local)
d := 24 * time.Hour
fmt.Println("in UTC", t.Truncate(d))
_, dif := t.Zone()
fmt.Println("in Local", t.Truncate(24 * time.Hour).Add(time.Second * time.Duration(-dif)))
func truncateToDay(t time.Time) {
nt, _ := time.Parse("2006-01-02", t.Format("2006-01-02"))
fmt.Println(nt)
}
This is not elegant but works.这不优雅,但有效。
I using theses functions on all my projects:我在所有项目中使用这些功能:
package time_utils
import "time"
func TruncateToStartOfDay(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
func TruncateToEndOfDay(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.