How many days until the end of the 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 to find the last day of the month
  • Having an array of 12 elements, maintaining the number of days in each month of the year
  • Simply using the date “YYYY-MM-31”.

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

  • Robin Salih

    To me the simple solution was the most obvious. I mean you wouldn’t seriously connect to a server to perform this calculation would you?

    Something like this in .net:

    DateTime date = DateTime.Today;
    int days = (new DateTime(date.Month == 12 ? date.Year + 1 : date.Year, date.Month == 12 ? 1 : date.Month + 1, 1) – date).TotalDays – 1;

    returns number of days left in the month (excluding current day).