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 ?
To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.
Add or subtract days from a date Enter your due dates in column A. Enter the number of days to add or subtract in column B. You can enter a negative number to subtract days from your start date, and a positive number to add to your date. In cell C2, enter =A2+B2, and copy down as needed.
The subtraction operator ( - ) subtracts the two operands, producing their difference.
To calculate the time between 2 dates in TypeScript, call the getTime() method on both dates when subtracting, e.g. date2. getTime() - date1. getTime() .
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
(2009,8,18) is NOT August 18th. It's September 18th.
You could call getTime() on each date object, then subtract the later from the earlier. This would give you the number of milliseconds difference between the two objects. From there, it's easy to get to days.
A couple of hiccups to watch for, though: 1) daylight savings time, and 2) ensuring your times are coming from the same time zone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With