go

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. 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. I read through the time.Time doc but didn't find a way to do it.


Solution

  • 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;

    func truncateToDay(t time.Time) time.Time {
        return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
    }
    

    here's a play example; https://play.golang.org/p/jnFuZxruKm