JRS: In article <11**********************@g10g2000cwb.googlegroups .com>

, dated Mon, 19 Jun 2006 08:06:17 remote, seen in

news:comp.lang.javascript,

ja********@hotmail.com posted :

I'm really sorry to post this as I know it must have been asked

countless times before, but I can't find an answer anywhere.

Then you are an unskilful looker.

Does anyone have a snippet of JavaScript code I could borrow which

calculated the difference in years and days between two dates, and

takes leap years into account?

I'm calculating the difference in the usual way, i.e....

var difference = dateTo.getTime() - dateFrom.getTime();

Usual? but nowadays many people know better. That gives the difference

in absolute time (ignoring Leap Seconds).

...and converting this millisecond value into days by using...

var daysDifference = (difference/1000/60/60/24);

864e5 is easier to write than 1000/60/60/24. However, one cannot rely

on civil days all being of that length.

But how do I then display the difference in days AND years? I've tried

the following:

var yearsDifference = Math.floor(daysDifference/365.25);

var daysLeft = Math.floor(daysDifference-(yearsDifference*365.25));

...but it gives me inaccuracies. For example, if I use my code to

calculate the difference between 05/01/1998 and 05/01/2000 it returns 1

year and 364 days!

But what are those dates? This is an international newsgroup, and dates

need to be presented unambiguously. Generally, the daycount difference

for those dates is 730 days; but where FFF is used it is 731 days.

Any assistance would be gratefully received!

You should have read the newsgroup FAQ before asking. Be aware that

Google did not invent newsgroups, which was done long before the Web

appeared; they merely provide an inferior interface, and do not give

adequate guidance in the established use of News.

Since the number of days in a year is not constant, there can be no one

correct answer. One can count the full years in the interval from the

beginning, and see how many days are left. Or one can do it in reverse.

Or one can determine the daycount difference, and do some approximation

to a rounded div/mod 365.25 or 365.2425. Or ...? The different methods

will, for at least some date combinations, give different answers. One

method is in js-date1.htm on my site.

If this is coursework, then, if the instructor is intelligent (one

cannot rely on that), the point of interest should be how thoughtfully

you treat the difficulties.

But if it is a real-world application, the originators of the situation

should have given an unambiguous indication of how the results should be

obtained.

--

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©

<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript

<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.

<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.