in javascript I got two dates. How to find the difference between two dates.
var first = document.getElemetById("first_date").value;
var last = document.getElemetById("last_date").value;
the date format is mm/dd/yyyy(07/19/2015);
how to find?

Recommended Answers

All 4 Replies

In Javascript this is never a simple task, at least for me, so I prefer to stick with libraries. While waiting for more appropriate suggestions, try with the difference() function in moments.js library:

Bye!

commented: +rep for moment - brilliant I use it a lot +15

In general convert each date into a number (of hours, minutes, seconds, whatever, depending on the degree of precision that you require) and then subtract one from the other. This can be a bit tricky with leap years and whatever.

In practice it might be easiest to convert your dates into Javascript Date objects [new Date(datestring) or new Date(year, month, day, etc.)] then convert these into the internal milisecond format [getTime()] and then just subtract them. Divide the result by the appropriate value if you need less than millisecond precision.

I could not move forward.

Can you suggest me how to do that with sample code

Try this code :

const date1 = new Date('7/13/2010');
const date2 = new Date('7/18/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
alert(diffDays);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.