Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  14] [ 2]  / answers: 1 / hits: 21886  / 15 Years ago, tue, august 18, 2009, 12:00:00

I am looking for a way to do proper subtraction between two javascript Date objects and get the day delta.



This is my approach but it fails for todays date as an input:



<script type=text/javascript>
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth,incomingDay);
var today = new Date();

var delta = incomingDate - today;
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));

//fails for the today as input, as expected 0 delta,instead gives 31:
alert(getDayDelta(2009,8,18));
</script>


What would be a better approach for this ?


More From » datetime

 Answers
5

The month number in the Date constructor function is zero based, you should substract one, and I think that is simplier to calculate the delta using the timestamp:



function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay),
today = new Date(), delta;
// EDIT: Set time portion of date to 0:00:00.000
// to match time portion of 'incomingDate'
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);

// Remove the time offset of the current date
today.setHours(0);
today.setMinutes(0);

delta = incomingDate - today;

return Math.round(delta / 1000 / 60 / 60/ 24);
}


getDayDelta(2008,8,18); // -365
getDayDelta(2009,8,18); // 0
getDayDelta(2009,9,18); // 31

[#98884] Friday, August 14, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;