Good evening

This is a story of how a simple presumption led to terrible bugs. And that dealing with time is difficult even in modern languages.

All I wanted to do was to get the same day in the next month.

The simplest solution coming to mind would be using the built-in AddDate, like this:

We gave it the 7th of April, it returns the 7th of May.

But this approach has a corner-case bug. If you put 31st of January 2019 there, it will output 3rd of March (it jumps to what would be considered 31st of February, and the applies normalization, making it equivalent to 3rd of March). Two calendar months ahead. This was definitely not what I wanted.

For my purposes, I had decided that I wanted it to show the last day of the next month if this day is not present in it, but it must output the next calendar month in any case.

This is not available in Golang out-of-the-box. Let’s implement it.

## Last day of month

This is comparatively easy. Found the answer here, I’ll just paste it here.

You essentially go to the first day of the current month (which is always the 1st), use AddDate to jump one month forward (to the 1st) and then one day backward, yielding the last day of the current month.

## Same day (or last) next month

Finally, let’s get the same day next month, or last one.

I simply use time.Date and assign data field by field. That way I circumvent normalization.

## Other functions

### Specified day within a month

These are a bit extended. In addition to the date, you provide a day you want to set the date to. But again, if this day does not exist within the given month, it will set it to last day. But they will always be within the calendar month: current or next, respectively.

### As a bonus

A function that returns the number of calendar days between dates (as if there were no times in them)

## In conclusion

Time is a fickle matter to tinker with. And most programming languages struggle with providing enough tools for all developers. Oh, and don’t get me started with timezones, please.

Thanks for tuning in!