← servoy magazine

[Tip] Get the Last Day of the Month

  • Tips

Enrico Arata
Automazione Aziendale - Torino - Italy

Do you need the last day of a month..but months carries 28 or 29 or 30 or 31 days??

Your only certainity is that the day after will be the first of a new month, so lets start from there and go back one day. By the way, one day in javascript (and in real life also) contains 86,400,000 milliseconds.

var wanted_last_day_date = new Date (Date.UTC(wanted_year, wanted_month+1, 1) - 864E5)

Notes:

864E5 is equivalent to 86400000 in exponent notation.

wanted_month (integer) is the number of your target month. Be carefull: javascripts Date's constructor considers months from 0 (january) to 11 (december).

You do not need to worry for december + 1 ... Date() switches years for you.

wanted_year (integer) contains your target year. Use 4 digits for millenium compatibility (2004 and not only 4).