time.Time Round to Day

前端 未结 4 1029
野趣味
野趣味 2021-02-01 13:32

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. For example, ts: 1305861602 corresponds to 2016-04-14,

4条回答
  •  天涯浪人
    2021-02-01 14:00

    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.

    If you are working in UTC:

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

    If you are not, you need to convert back and forth to UTC

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

提交回复
热议问题