To find the number of days until the end of the month, compare with the first day of the next month

It's a common enough problem, you want to find out if a date is in a particular month, or you want to know how many days there are left in the current month, and so on.

I've seen the following awkward solution plenty of times at different companies: To find out if a day is within a month, you see if the date in question is greater than the start of the month and less than the end of the month; this seems logical enough. To determine the number of days left, you subtract the date in question from the last date in the month; this also seems reasonable enough.

The trouble is it's not particularly easy to find out the last date in a given month. I've seen at least the following solutions:

Using database functions is the best, for sure, as they'll do the calculations right, but it's still a certain amount of work to connect to the database just for this purpose. Obviously there are libraries such as Java's Calendar which will do the same work but again, it's a certain amount of effort. The array isn't good as you have to introduce further logic to handle leap years. The last approach is obviously ridiculous as there are plenty of months for which such a date is invalid. (But MySQL 4 allows such dates and MySQL 5 doesn't; which as part of a database migration project has brought this point to my attention.)

However, there is a much simpler solution, that is to compare the date with the first day of the next month. Finding the next month is easy (there are always 12 months in the year).

This article is © Adrian Smith.
It was originally published on 27 Jul 2011
More on: Algorithms