5

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.

7
  • Could you be more specific than "is it safe"? What doubts do you have about this method? Have you tested it? Feb 6, 2021 at 7:33
  • I think the only edge case you need to take into account here is that some time never actually ocurred, and some times occured twice (1 hour on the daylight savings shift). From my knowledge all languages who shift does so at 2 AM though, so if your just interested in midnight then that should never be an issue.
    – super
    Feb 6, 2021 at 7:49
  • Good to know about the 2am rule of thumb. @HymnsForDisco Yes I can clarify. I wonder if creating a date with time.Date(2020, 10, 40) is a reliable way of creating a date for instance, that is all extra days of the month will still be added to the date. I did some testing and it seems to work in my usecase.
    – Ado Ren
    Feb 6, 2021 at 8:01
  • golang.org/pkg/time/#Time.AddDate
    – Volker
    Feb 6, 2021 at 9:47
  • related? Add days to date in Go May 11, 2021 at 9:49

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.