Subtract javascript date

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

This is my approach, but it is not suitable for today's date as 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 better for this?

+7
javascript date datetime
source share
4 answers

The number of months in the Date constructor function is based on a zero value, you should subtract it, and I think it’s easier to calculate the delta using a 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 
+7
source share

(2009,8,18) NOT August 18th. This is September 18th.

+6
source share

You can call getTime () for each date object, and then subtract later from the previous one. This will give you the difference in milliseconds between the two objects. From there it is easy to get to the days.

A few hiccups to watch out for, though: 1) daylight saving time and 2) ensuring that your time comes from the same time zone.

+5
source share

This will work better, but it does not cope with negative values ​​of the result. You might just want to analyze the values ​​yourself and deal with them.

 function getDayDelta(incomingYear,incomingMonth,incomingDay){ var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay); var today = new Date(); today = new Date(Date.parse(today.format("yyyy/MM/dd"))); var delta = incomingDate - today; if (delta == 0) { return 0; } var resultDate = new Date(delta); return resultDate.getDate(); } //works for the future dates: alert(getDayDelta(2009,9,10)); alert(getDayDelta(2009,8,19)); alert(getDayDelta(2009, 8, 18)); 
0
source share

All Articles