pingeyeg
pingeyeg

Reputation: 680

Trying to get the days from subtracting two different dates

I'm trying to figure out how to subtract two different dates to get the remainder. Based on my Google searches, this seems like it should be pretty straight forward, but my code just isn't working as expected.

const options = { year: 'numeric', month: 'numeric', day: 'numeric' };
let today = new Date();
today = today.toLocaleDateString('en-US', options); // '2/20/2019'
dueDate = new Date(dueDate[0]);
dueDate = dueDate.toLocaleDateString('en-US', options); // '12/15/2019'
daysLeft = today.setDate(today.setDate() - dueDate); // Being declared as a let outside the scope block

The error message I'm receiving is: Uncaught (in promise) TypeError: today.setDate is not a function

enter image description here

UPDATE:

The possible duplicate answer almost helped me, but it doesn't account for the years so 2/20/2019 - 2/1/2001 is outputting 19, which is incorrect.

Upvotes: 1

Views: 217

Answers (3)

Vladimir Bogomolov
Vladimir Bogomolov

Reputation: 1794

You can use straight math.

let today = new Date();
let dueDate = new Date('12/15/2019');
let difference = Math.abs(Math.round((today.getTime()-dueDate.getTime())/1000/24/60/60));
console.log(difference);

This way we get the difference in milliseconds, and divide by 1000 to get seconds, by 60 to get minutes, by 60 again to get hours and by 24 finally to get days difference.

Upvotes: 3

Tushar Walzade
Tushar Walzade

Reputation: 3819

MomentJS is your friend! You could simply use a diff() as follows -

moment.locale('en-US');		 // setting locale
var today = moment();		 // current date
var dueDate = moment('12/15/2019', "MM/DD/YYYY");	// due date
console.log(Math.abs(dueDate.diff(today, 'days')));	// difference in days, possible values are months, years...
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

  • Note: Math.abs() avoids negative values if you provide a historical date!

Upvotes: 1

Ashkan Pourghasem
Ashkan Pourghasem

Reputation: 748

Well the main problem is you're parsing the date today to a string and then you're calling a method on it, which is naturally gonna fail. You should assign the value of today.toLocaleDateString('en-US', options), which is a string, to another variable and use the method on the variable that actually has the Date object inside. This is assuming the rest of the code is fine.

Upvotes: 1

Related Questions