Question

i have created below function to get date difference between two dates.. pleas check it that its correct as well as how to find no of month (multiply by 30 or 31 ?) and year..

function days_between(date1, date2,datepart) {

// The number of milliseconds in one day
 var ONE_DAY=0;
 if ( datepart === undefined ) {
  datepart = 'D';
}

 if(datepart='Y')
 {     
 ONE_DAY = 1000 * 60 * 60 * 24 * 30 *12
 }
 else if (datepart='M')
 {
 ONE_DAY = 1000 * 60 * 60 * 24 * 30
 }
 else
 {
 ONE_DAY = 1000 * 60 * 60 * 24   //for day
 }

// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()

// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)

// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)

}

Was it helpful?

Solution

If your application is going to require a lot of date manipulation methods, you may want to consider using something like the Datejs library.

If you include time.js from the Datejs library, you would be able to do the following:

var future = new Date().add({months: 5}); 
var now = new Date();

var span = new TimeSpan(future - now);

console.log("Days: ", span.getDays());

The time.js script is optional and is not included in the compiled /build/ versions. You can download it directly from the SVN repository.

OTHER TIPS

You should transform in days after making the difference not before. Like:

var d1 = new Date().getTime(),
d2 = new Date(2010, 11, 31).getTime();
alert(Math.round((d2-d1)/24/60/60/1000) + ' days left for 2010');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow