1

I need to compare two dates using best accuracy, for me day will be ok and take into consideration leap years.

It is possible ? I for now only create function to compare month accurancy :/

4 Answers 4

2

You can subtract Date object from another Date object and return microseconds

var d= new Date('2012/11/29');
var a= new Date('2012/11/30');
alert( (a-d) /(1000*24*60*60)) ); /* returns 1 */
Sign up to request clarification or add additional context in comments.

Comments

2

If you have date strings, you can parse them by using Date.parse("datestring"). It will return long(time in milliseconds). And you can compare any two longs.

var date1 = new Date("10/25/2011");
var date2 = new Date("09/03/2010");
var date3 = new Date(Date.parse(date1) - Date.parse(date2));

var dayDiff = date3.getDate() - 1;
var monthDiff = date3.getMonth();
var yearDiff = date3.getFullYear() - 1970;

Here is jsfiddle to test it.

2 Comments

Will this miliseconds consider leap years ? How can I convert miliseconds to days ? I have birth date and drive license date and I want to calculate that person have 17 years when pass license...
I've edited my answer with some piece of code. You can test it.
1

The best JavaScript Time and Date manipulation library I've come across is Moment.js

Getting the # of days between two dates:

d1 = moment('2012-10-31')
d2 = moment('2012-11-02')
Math.abs(moment.duration(d1-d2, 'ms').days())
// => 2

The default precision is milliseconds.

2 Comments

@KKyle Burton have always used date.js which has been around a long time. Really like moment.js docs!
dayjs is much more lightweight than momentjs
1

This should work for difference in days with fairly good precision:

function daysSince( past ) {
  return 0|( new Date().getTime() - past.getTime() ) * 1.16e-8;
}

console.log( daysSince( new Date('10/03/2012') ) ); //=> 31

Edit: Actually, if you only want to know the difference between two dates you can always return a positive number.

function daysBetweenDates( d1,d2 ) {
  return Math.abs( 0|( d1.getTime() - d2.getTime() ) * 1.16e-8 );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.