I am trying to use datejs (date ninja or whathaveyou..) and I am getting odd results. Here's what I output to console to test.
var d1 = Date.today();
var d2 = Date.parse(work.tax_credit_start);
var span2 = new TimeSpan(d2 - d1);
console.log('result of timespan test = ' + span2.getDays() + 'days between now and ' + Date.parse(work.tax_credit_start).toString('dd-mm-yyyy') + ' - ' + work.tax_credit_start );
I am expecting about -584 days according to date calculations in excel and other online services. Here's what I got:
result of timespan test = -462days between now and 30-00-2010 - 30-06-2010
I have got a localisation file for datejs for New Zealand style dates too, so I am not expecting that to be an issue. Though it appears to be the issue. Also if I parse a date and then render it as a string in the same format that it was in before being parsed it should not change yeah?
Long day, maybe I just need a break. Your thoughts/help internets?
Firstly, 30-00-2010 will be resolved as Wed Dec 30 2009 00:00:00. Is that what you really want?
Secondly, the difference in days between 30-00-2010 and 30-06-2010 is only a couple of days more than 6 months, how do you get -584 days? I get -182.
Anyway, it's not a difficult calculation. Create two date objects for the required dates, set their time to noon (so as to remove daylight saving issues across dates), subtract one from the other, divide the result by the number of milliseconds in a day (24 * 60 * 60 * 1000) and round to the nearest integer.
Here's a some quick functions to do the job:
// Iput as d/m/y or d-m-y
function dmyToDate(s) {
var bits = s.split(/[-/]/);
return new Date(bits[2], --bits[1], bits[0]);
}
// Difference between dates in days. If only one date supplied,
// today is used for endDate
// Copy startDate so don't mess it up
function daysBetweenDates(startDate, endDate) {
endDate = typeof endDate == 'string'? dmyToDate(endDate) : new Date();
startDate = typeof startDate == 'string'? dmyToDate(startDate) : new Date(startDate);
endDate.setHours(12,0,0);
startDate.setHours(12,0,0);
var diff = startDate - endDate;
var ms = 24 * 60 * 60 * 1000; // or 8.64e7
return Math.round(diff/ms);
}