time.Time Round to Day

前端 未结 4 1022
野趣味
野趣味 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 13:54

    The simple way to do this is to create new Time using the previous one and only assigning the year month and day. 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

    0 讨论(0)
  • 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)) 
    
    0 讨论(0)
  • 2021-02-01 14:01

    You can simply use duration 24 * time.Hour to truncate time.

    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

    0 讨论(0)
  • 2021-02-01 14:12

    in addition to sticky's answer to get the local Truncate do like this

    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)))
    
    0 讨论(0)
提交回复
热议问题