time.Time Round to Day

Go

Go Problem Overview


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.

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

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

Solution 3 - Go

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

Solution 4 - Go

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

Solution 5 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ FreebirdView Question on Stackoverflow
Solution 1 - GoevanmcdonnalView Answer on Stackoverflow
Solution 2 - GoshickyView Answer on Stackoverflow
Solution 3 - GoRichardView Answer on Stackoverflow
Solution 4 - GoIsaac WeingartenView Answer on Stackoverflow
Solution 5 - GoLinuxeaView Answer on Stackoverflow