-6

Want to display last day of the previous month using JS.

I need pure JS code than other Library.

Format Needed : Jan 31, 2017

Sarath
  • 207
  • 1
  • 2
  • 7

1 Answers1

1

I always use Moment.js whenever I want work with dates which gives you lot's of options for format your date, but since you said with plain javascript, you can made a method like this to format your date :

function formatDate(date) {
   date.setDate(0);
   var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
 ];

 var day = date.getDate();
 var monthIndex = date.getMonth();
 var year = date.getFullYear();

 return  monthNames[monthIndex] +  ' ' + day  + ' ' + year;
}

console.log(formatDate(new Date())); 

Basiclly date.setDate(0); will change the date to last day of the previous month.

Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
  • Thanks @Emad Dehnavi - Helped me a lot – Sarath Nov 03 '17 at 09:34
  • For anyone stumbling across this in 2021: `date.toLocaleDateString('en-US', {year: 'numeric', month: 'long', day: 'numeric' })` will achieve the same as above without the array of month names, and `date.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric' })` will give the format the OP asked for. – OffBy0x01 Sep 21 '21 at 11:28