Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Saturday 1 December 2012

How To Get Last Day Of Previous Month | Javascript

While working on client side technologies like Javascript or Jquery there come many times when you need to get the last day of the month. Today's tutorial will explain you how to get last day of previous month using JavaScript.

Scenario:-

The scenario is we know that current date of the month is e.g. Dec 02, 2012 and we need to get last day of previous month. So here we go

 
var currentDate =new Date();   
// Will return the current date.e.g 12/02/2012
  alert(currentDate);            
  //     12/02/2012 Dec 02, 2012
 currentDate.setDate(0);
  alert(currentDate);
 // Will get last day of previous month  
 // 11/30/2012 Nov 30, 2012   and same is going on with the below lines.

 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);
 currentDate.setDate(0);
  alert(currentDate);

In the above example we use setDate() built-in function of JavaScript which takes an integer value as parameter to represent the day of the month. E.g. 0 will represent the last day of the previous month and -1 will represent the day before the last day of the previous month.

No comments:

Post a Comment

Please do not enter spam links.