Ado Ren
Ado Ren

Reputation: 4404

How to add days to date

I want to get next day @ midnight of a given date. So far I'm using:

givenDate.Add(time.Hour * time.Duration(24))

Problem is with certain timezones where I stay on the same day if I add 24h. In France, they change hours once in a while.

Is it safe to use the following to add a single day ?

time.Date(givenDate.Year(), givenDate.Month(), givenDate.Day()+1, 0, 0, 0, 0, loc)

loc being time.UTC in the given example.

Upvotes: 5

Views: 2077

Answers (1)

icza
icza

Reputation: 418387

Your proposed solution is "safe" and good:

t2 := time.Date(givenDate.Year(), givenDate.Month(), givenDate.Day()+1, 0, 0, 0, 0, loc)

You could make it faster with:

y, m, d := givenDate.Date()
t2 := time.Date(y, m, d+1, 0, 0, 0, 0, loc)

As Time.Date() returns you the date components in one call, and if you check the implementation, the Time.Year(), Time.Month() and Time.Day() methods all call the same Time.date() (unexported) method under the hood (3 times in your case), just like Time.Date().

time.Date() documents that:

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

So the documentation states that the location is taken into account, and if you pass 0 for hour, min, sec, nanonsec, those will be 0 in the given zone.

Upvotes: 3

Related Questions