473,573 Members | 3,213 Online

# Calculate difference in dates

For my website i would like to display the age of my son in years,
months, days and hours.

For now i manage to get a result for totals. Like the total number of
days.

This is the beginning:

starttime = Date.parse("Aug 10,2003, 07:07")
sdt = new Date(starttime)
starttime= Math.ceil((star ttime) / 1000 / 60 / 60 / 24 )
ndt = new Date()

y = sdt.getYear()
m = sdt.getMonth() + 1
d = sdt.getDate()
h = starttime

Thanx
Jul 23 '05 #1
26 4381
Frank wrote on 29 aug 2004 in comp.lang.javas cript:
For my website i would like to display the age of my son in years,
months, days and hours.

For now i manage to get a result for totals. Like the total number of
days.

This is the beginning:

starttime = Date.parse("Aug 10,2003, 07:07")
sdt = new Date(starttime)
starttime= Math.ceil((star ttime) / 1000 / 60 / 60 / 24 )
ndt = new Date()

y = sdt.getYear()
m = sdt.getMonth() + 1
d = sdt.getDate()
h = starttime

<http://www.merlyn.demo n.co.uk/js-date0.htm#DC>
and
<http://www.merlyn.demo n.co.uk/js-date1.htm#diff>
--
Evertjan.
The Netherlands.
but let us keep the discussions in the newsgroup)

Jul 23 '05 #2
On 29 Aug 2004 08:18:46 -0700, Frank <fa*****@hotmai l.com> wrote:
For my website i would like to display the age of my son in years,
months, days and hours.

For now i manage to get a result for totals. Like the total number of
days.

This is the beginning:

starttime = Date.parse("Aug 10,2003, 07:07")

It would be safer to use numbers, rather than a string as there is no
exact definition for string date formats. I'm certain that the format
above will cause problems in some browsers.

var birth = new Date(2003, 7, 10, 7, 7);

[snip]

Calculating differences in dates is simply a matter of subtracting one
Date object from another. This will yield a number representing the
milliseconds. You can then use a new Date object to return the number of
years, months, days and hours:

var difference = new Date(new Date() - birth),
years = difference.getF ullYear() - 1970,
months = difference.getM onth(),
days = difference.getD ate() - 1,
hours = difference.getH ours(),
t = new String(years);

The adjustments above are based on the fact that a time of zero (0)
represents the date, 01-Jan-1970 00:00:00 GMT. The adjustments make the
respective values zero-based.

t += ' year';
if(1 != years) {t += 's';}
t += ', ' + months + ' month';
if(1 == months) {t += 's';}
t += ', ' + days + ' day';
if(1 == days) {t += 's';}
t += ', and ' + hours + ' hour';
if(1 == hours) {t += 's';}

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
JRS: In article <opsdh37io1x13k vk@atlantis>, dated Sun, 29 Aug 2004
16:01:43, seen in news:comp.lang. javascript, Michael Winter <M.Winter@bl
ueyonder.co.inv alid> posted :
On 29 Aug 2004 08:18:46 -0700, Frank <fa*****@hotmai l.com> wrote:
For my website i would like to display the age of my son in years,
months, days and hours.

For now i manage to get a result for totals. Like the total number of
days.

This is the beginning:

starttime = Date.parse("Aug 10,2003, 07:07")
It would be safer to use numbers, rather than a string as there is no
exact definition for string date formats. I'm certain that the format
above will cause problems in some browsers.

Can anyone provide an actual example of failure? ISTM worth settling
the point of whether all javascript systems, however configured, can
read a date with English-MON DD YYYY in arbitrary order and
reasonable punctuation.
var birth = new Date(2003, 7, 10, 7, 7);
Not fully equivalent, though; the first returns a time_t (ms) and the
second a Date Object.

That form uses Month-1, and hence is amenable to human error; I'd
suggest new Date("2003/08/10 07:07") , in which the string looks like
the right date and is as near ISO-8601 as my system accepts. Again, can
anyone find an example of failure of that form?

[snip]

Calculating differences in dates is simply a matter of subtracting one
Date object from another.
No. It does give the absolute time interval.
This will yield a number representing the
milliseconds .
Yes.
You can then use a new Date object to return the number of
years, months, days and hours:
No; *a* number of ...

Consider a boy born 2004-01-01 00:00:00; at 2008-12-31 12:00:00 he will
be nearly 5 years old, and looking forward to his party on the next day.
He will be 1461 + 365.5 days old.

Consider a boy born 1970-01-01 00:00:00; he will be 1461 + 365.5 days
old on 1975-01-01 12:00:00 he will be 5 years old, and looking forward
to his party on that afternoon.
A boy born 2004-02-01 will be a month old on 2004-03-01 ; 29 days.
A boy born 2005-02-01 will be a month old on 2005-03-01 ; 28 days.
Starting from 1970-01-01, 29/28 days is not yet a month.

The lad was 6 months old on 2004-02-10;

starttime = Date.parse("Aug 10,2003, 07:07")
finaltime = Date.parse("Feb 10,2004, 07:07")

D = new Date(finaltime-starttime)

gives me Sat Jul 4 02:00:00 UTC+0100 1970 -> 6 mo 3 dy 2 hr; the
same every year, since the end of Feb real time is not crossed.
Now consider those, of all ages, who were born on March 28th at noon.
They will have been a week old on the following April 4th, at noon. But
in Europe[~] 3/7 of them will then have been an hour younger than the
other 4/7; and probably /vice versa/ in much of the USA.

[~] EU & neighbours; but not Iceland (there may be other exceptions).

Moreover, the lad may be a foreigner. Differences from GMT will be
(too) properly allowed for in determining the interval; but datum is
1970.0 GMT. Your method, which adds diff to datum and then uses the
getFullYear family, gives a result depending on the location of the
answering system. Few places use GMT as civil time year-round.
t += ' year';
if(1 != years) {t += 's';}
t += ', ' + months + ' month';
if(1 == months) {t += 's';}
t += ', ' + days + ' day';
if(1 == days) {t += 's';}
t += ', and ' + hours + ' hour';
if(1 == hours) {t += 's';}

Erroneous pluralisation?

IMHO, the OP needs to step forwards in integer civil years from the DoB
until the next step will pass the present instant, counting them; then
likewise in months, days, hours, and minutes.

He could step backwards; I expect that the answer will sometimes[*]
differ.
[*] Assuming that the OP repeats the test for a statistically-
significant[+] number of sons[#].
[+] Which need not be all his own.
[#] Or daughters, wives, etc.
A further correction, probably of about 9 months, will be needed if the
lad is Korean (4.5 mo if half-Korean?), and the stated date is DoB.
See via below.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #4
On Mon, 30 Aug 2004 17:19:23 +0100, Dr John Stockton
<sp**@merlyn.de mon.co.uk> wrote:
JRS: In article <opsdh37io1x13k vk@atlantis>, dated Sun, 29 Aug 2004
16:01:43, seen in news:comp.lang. javascript, Michael Winter
<M.******@bluey onder.co.invali d> posted :
On 29 Aug 2004 08:18:46 -0700, Frank <fa*****@hotmai l.com> wrote:
[snip]
starttime = Date.parse("Aug 10,2003, 07:07")
It would be safer to use numbers, rather than a string as there is no
exact definition for string date formats. I'm certain that the format
above will cause problems in some browsers.

Can anyone provide an actual example of failure? ISTM worth settling
the point of whether all javascript systems, however configured, can
read a date with English-MON DD YYYY in arbitrary order and
reasonable punctuation.

Would it be possible? As there is no definition on what should result, or
be accepted, in any of the string-related methods, it would be up to the
developers to decide what should be a reasonable format. That said, I
agree: it would be nice to know.
var birth = new Date(2003, 7, 10, 7, 7);

Not fully equivalent, though; the first returns a time_t (ms) and the
second a Date Object.

That form uses Month-1, and hence is amenable to human error;

True. I did mean to describe the arguments. However, once documented, it
shouldn't be of any concern.

So, for that description...

var birth = new Date(
2003, // Year
7, // Month, starting from zero. 0-Jan 1-Feb 2-March ...
10, // Date
7, // Hours
7); // Minutes

[snip]
Calculating differences in dates is simply a matter of subtracting one
Date object from another.

No. It does give the absolute time interval.

Could you explain what you see as the difference? Is it a matter of
semantics, or something more substantial?

[snip]
You can then use a new Date object to return the number of
years, months, days and hours:
[snipped long example]

Hmm. Yes, I see the problem.
t += ' year';
if(1 != years) {t += 's';}
t += ', ' + months + ' month';
if(1 == months) {t += 's';}
t += ', ' + days + ' day';
if(1 == days) {t += 's';}
t += ', and ' + hours + ' hour';
if(1 == hours) {t += 's';}

Erroneous pluralisation?

Unfortunately. When I tested what I wrote, I corrected that sequence but I
didn't copy the changes back to my post. The comparisons should all be
"not equal".

[snip]

It never ceases to amaze me how something as seemingly simple as date
manipulation can turn into such a minefield.

Thank you,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message news:<opsdh37io 1x13kvk@atlanti s>...
var birth = new Date(2003, 7, 10, 7, 7);
var difference = new Date(new Date() - birth),
years = difference.getF ullYear() - 1970,
months = difference.getM onth(),
days = difference.getD ate() - 1,
hours = difference.getH ours(),
t = new String(years);

t += ' year';
if(1 != years) {t += 's';}
t += ', ' + months + ' month';
if(1 == months) {t += 's';}
t += ', ' + days + ' day';
if(1 == days) {t += 's';}
t += ', and ' + hours + ' hour';
if(1 == hours) {t += 's';}

Hi Thanks you both for responding.
Jul 23 '05 #6
Hi i'm sorry but this is i think a bit over my head as a newbe.

Do you guys have a complete answer for me, because i got lost.
I really appriciate the input.

Jul 23 '05 #7
On 29 Aug 2004 08:18:46 -0700, fa*****@hotmail .com (Frank) wrote:
For my website i would like to display the age of my son in years,
months, days and hours.

Frank - if you ever get/got this to work could you please post the
code? I've been looking to do the exact same thing for a good two
years now. Every once in a while I seach the net for code but the
best I can find only gives total number of days, months, etc (ie: 30
months, 919 days, etc). In fact this is the very reason I'm reading
this group now!

I don't know anything about javascript so I am completely lost.

Eternally grateful,

-Otter
Jul 23 '05 #8
Hi guys

This won't immediately solve your problems, but it will go a long way to
showing you what's involved. Anyway, it's more fun to do some of the work
yourselves :-)

/////////////////////////////////////////////////////////////////////////
// //
// These functions access the user's local date and time. //
// //
/////////////////////////////////////////////////////////////////////////

//
// This function returns the date.
//
function getDateNow () {
var dayNames = new
Array("Sunday", "Monday","Tuesd ay","Wednesday" ,"Thursday","Fr iday","Saturday "
);
var monthNames = new
Array("January" ,"February","Ma rch","April","M ay","June","Jul y","August","Se p
tember","Octobe r","November"," December");
var theDate = new Date;

return dayNames[theDate.getDay( )] + ", " + monthNames[theDate.getMont h()]
+ ", " + theDate.getDate ();
}

//
// This function returns the time in 12-hour clock format.
//
function getTimeNow () {
var theDate = new Date;

return showZeroFill(sh owTheHour(theDa te.getHours())) + ":" +
showZeroFill(th eDate.getMinute s()) + ":" +
showZeroFill(th eDate.getSecond s()) + " " + showAMPM(theDat e);
}

//
// Mos people using this site are not likely to be familiar with the 24-hour
clock,
// or "military time". So this, used in conjunction with "showAMPM", makes
sure that
// times are described in the more familiar format.
//
function showTheHour (theHour) {
if ((theHour > 0) && (theHour < 13)) {
return theHour;
}
else {
if (theHour == 0) {
return theHour;
}
else {
return (theHour - 12);
}
}
}

//
// Pad the a time value with a 0 to the left, if it is less than 10.
//
function showZeroFill (theValue) {
if (theValue > 9) {
return theValue;
}
else {
return "0" + theValue;
}
}

//
// Return "AM" or "PM" according to the hour of the time.
//
function showAMPM (theDate) {
if (theDate.getHou rs() < 12) {
return "AM";
}
else {
return "PM";
}
}

On 2004/09/06 12:22, in article 14************* *************** ****@4ax.com,
"Otter" <Ot***@nospam.n et> wrote:
On 29 Aug 2004 08:18:46 -0700, fa*****@hotmail .com (Frank) wrote:
For my website i would like to display the age of my son in years,
months, days and hours.

Frank - if you ever get/got this to work could you please post the
code? I've been looking to do the exact same thing for a good two
years now. Every once in a while I seach the net for code but the
best I can find only gives total number of days, months, etc (ie: 30
months, 919 days, etc). In fact this is the very reason I'm reading
this group now!

I don't know anything about javascript so I am completely lost.

Eternally grateful,

-Otter

Jul 23 '05 #9
"Otter" <Ot***@nospam.n et> wrote:
On 29 Aug 2004 08:18:46 -0700, fa*****@hotmail .com (Frank) wrote:
For my website i would like to display the age of my son in years,
months, days and hours.

Frank - if you ever get/got this to work could you please post the
code? I've been looking to do the exact same thing for a good two
years now. Every once in a while I seach the net for code but the
best I can find only gives total number of days, months, etc (ie: 30
months, 919 days, etc). In fact this is the very reason I'm reading
this group now!

I don't know anything about javascript so I am completely lost.

Eternally grateful,

-Otter

------------------------------------------------------------------------------------------------------------------------

I have a section on my web page called "Clocks." Here's the URL:

http://users.stans.net/kfeiler/stuff/clocks/clocks.htm

It's not exactly what you want, but it's close. "Clocks" are
countdown clocks from the current date and time to some future
date/time. You might use one, for instance, to determine exactly how
long (in years, days, hours, minutes, and seconds) it is until you
retire, or until your birthday, or to the year 10,000, etc.

What you're after is a little different. You want the elapsed time
from some past event (your son's birthday) to the present. I suspect
that you could use most of the Javascript code in Clocks for what you
want, but you'd have to make changes. It's all downloadable. If you'd
instructions.
Regards,
Kent Feiler
www.KentFeiler.com
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.