time.Time Round to Day

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


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


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

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

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.