views:

75

answers:

2

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)

}

+2  A: 

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.

Daniel Vassallo
this is exactly what i want.. let me check..
Rajesh Rolen- DotNet Developer
getting this error : Error: (new Date).add is not a functionSource File: http://localhost/td/searchhotels.aspxLine: 319
Rajesh Rolen- DotNet Developer
@DotNetDeveloper: Make sure you have included 'time.js'. The file is optional and is not included in the compiled /build/ versions. You can download it here: http://code.google.com/p/datejs/source/browse/trunk/src/time.js
Daniel Vassallo
I have just tested it in firebug, and it worked fine.
Daniel Vassallo
A: 

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');
Mic
oh sorry, you need to know if you are a leap year
Mic
I use date.js too for these calculations
Mic
can u please give me any like of date.js to show date.diff
Rajesh Rolen- DotNet Developer
I use addMonths, addYears in a loop and compare with the other value, but I don't have big gaps. Another option you could consider is to convert the dates in arrays if d is a date ttype [d.getFullYear(), d.getMonth()+1, d.getDate()], and compute years and months, and you avoid the leap years and day count problem.
Mic