Search code examples
javascriptdatedate-conversion

Get last day of the month from '2015-02-23' string (javascript)


I have a string that represents a date in this format: 2015-02-23

I need to use this date to get the last day of the month. How should I do the necessary conversions to achieve that?


Solution

  • Here's a function that should work for you:

    function getLastDayInMonth(s) {
      var date = new Date(s);
      var lastDate = date;
      var month = date.getMonth();
      
      while (date.getMonth() == month) {
        lastDate = date;
        date = new Date(lastDate.getTime() + 1000 * 60 * 60 * 24); //add 1 day
      }
      return lastDate.toDateString();
    }
    
    var lastDay = getLastDayInMonth('2015-02-23');
    alert(lastDay);