Calculate difference in dates

F

Frank

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((starttime) / 1000 / 60 / 60 / 24 )
ndt = new Date()

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

Thanx
 
E

Evertjan.

Frank wrote on 29 aug 2004 in comp.lang.javascript:
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((starttime) / 1000 / 60 / 60 / 24 )
ndt = new Date()

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

A bit young for your son toread the web ;-}

Read the faq:

<http://www.merlyn.demon.co.uk/js-date0.htm#DC>
and
<http://www.merlyn.demon.co.uk/js-date1.htm#diff>
 
M

Michael Winter

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.getFullYear() - 1970,
months = difference.getMonth(),
days = difference.getDate() - 1,
hours = difference.getHours(),
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';}
alert(t);

Hope that helps,
Mike
 
D

Dr John Stockton

JRS: In article <opsdh37io1x13kvk@atlantis>, dated Sun, 29 Aug 2004
16:01:43, seen in Michael Winter <M.Winter@bl
ueyonder.co.invalid> posted :
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';}
alert(t);

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.
 
M

Michael Winter

JRS: In article <opsdh37io1x13kvk@atlantis>, dated Sun, 29 Aug 2004
16:01:43, seen in Michael Winter
On 29 Aug 2004 08:18:46 -0700, Frank <[email protected]> wrote:
[snip]
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.
Not fully equivalent, though; the first returns a time_t (ms) and the
second a Date Object.

Yes. Sorry about that.
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]
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]

[snipped long example]

Hmm. Yes, I see the problem.
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
 
F

Frank

Michael Winter said:
var birth = new Date(2003, 7, 10, 7, 7);
var difference = new Date(new Date() - birth),
years = difference.getFullYear() - 1970,
months = difference.getMonth(),
days = difference.getDate() - 1,
hours = difference.getHours(),
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';}
alert(t);

Hi Thanks you both for responding.
 
F

Frank

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.

Thanx in advance.
 
O

Otter

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

Ian Sedwell

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","Tuesday","Wednesday","Thursday","Friday","Saturday"
);
var monthNames = new
Array("January","February","March","April","May","June","July","August","Sep
tember","October","November","December");
var theDate = new Date;

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

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

return showZeroFill(showTheHour(theDate.getHours())) + ":" +
showZeroFill(theDate.getMinutes()) + ":" +
showZeroFill(theDate.getSeconds()) + " " + showAMPM(theDate);
}

//
// 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.getHours() < 12) {
return "AM";
}
else {
return "PM";
}
}
 
D

Dr John Stockton

JRS: In article <opsdj5hefsx13kvk@atlantis>, dated Mon, 30 Aug 2004
18:22:38, seen in Michael Winter <M.Winter@bl
ueyonder.co.invalid> posted :
JRS: In article <opsdh37io1x13kvk@atlantis>, dated Sun, 29 Aug 2004
16:01:43, seen in Michael Winter
On 29 Aug 2004 08:18:46 -0700, Frank <[email protected]> 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.


Certainly it would be possible. The three-letter abbreviation must be
the month; ignoring case, jan..dec, all else being an error. The four
digits must be the year, so the other field the day.

There is the question of what punctuation is reasonable; in mine, f,eb
gives NaN, but fe,b is OK (and GMT+2); an isolatable letter appears to
be taken as offset (j excluded).

My MSIE4 system accepts
Feb 3 2222 YES
Feb 3st 2222 NO
Feb 3nd 2222 NO
Feb 3rd 2222 NO
Feb 3th 2222 YES
where the last two are alarming.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Mon, 6 Sep 2004 06:22:12, seen in Otter
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!

Evertjan wrote :-

Read the faq:

<http://www.merlyn.demon.co.uk/js-date0.htm#DC>
and
<http://www.merlyn.demon.co.uk/js-date1.htm#diff>

but perhaps he missed
<URL:http://www.merlyn.demon.co.uk/js-dates.htm#Intro> !
 
D

Dr John Stockton

JRS: In article <BD624545.CDE5%[email protected]>, dated Mon, 6
Sep 2004 15:46:19, seen in Ian Sedwell
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 :)

It seems rather a pointless contribution. Did you write it yourself?

Code posted in News should not be allowed to be line-wrapped by the
posting software; the poster should wrap it by hand himself. Or
herself.
// This function returns the time in 12-hour clock format.

A silly thing to do.

// Mos people using this site are not likely to be familiar with the 24-hour
clock,

Most people here know it well; even the Americans.

function showTheHour (theHour) {
if ((theHour > 0) && (theHour < 13)) {
return theHour;
}
else {
if (theHour == 0) {
return theHour;
}
else {
return (theHour - 12);
}
}
}

ISTM that the above code does not do the customary thing for the first
hour of the day; but I've not run the code.

On 2004/09/06 12:22, in article (e-mail address removed),
"Otter" <[email protected]> wrote:

Responses should go after trimmed quotes.

Carefully reading a newsgroup FAQ before posting to the group is
strongly recommended; anyone who posts an answer palpably inferior to
one indicated by the FAQ is liable to be considered, and described as,
injudicious.
 
K

Kent Feiler

Otter said:
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
like to look at it, check the HEEEELP section for download
instructions.


Regards,


Kent Feiler
www.KentFeiler.com
 
I

Ian Sedwell

JRS: In article <BD624545.CDE5%[email protected]>, dated Mon, 6
Sep 2004 15:46:19, seen in Ian Sedwell


It seems rather a pointless contribution. Did you write it yourself?

Yes I did.
Code posted in News should not be allowed to be line-wrapped by the
posting software; the poster should wrap it by hand himself. Or
herself.


A silly thing to do.

Please explain that to my client and everyone else who prefers the 12-hour
clock. I prefer the 24-hour clock personally, but then I had it drummed into
my head during flying training.
Most people here know it well; even the Americans.

Why should we expect the Americans to have an inferior intelligence?
ISTM that the above code does not do the customary thing for the first
hour of the day; but I've not run the code.

It works very well.
Responses should go after trimmed quotes.

Carefully reading a newsgroup FAQ before posting to the group is
strongly recommended; anyone who posts an answer palpably inferior to
one indicated by the FAQ is liable to be considered, and described as,
injudicious.

I hope that no one ever describes you as an arrogant toe-rag. That would be
palpably injudicious.
 
M

Mick White

function showTheHour (theHour){
return theHour==0?12:theHour<13?theHour:theHour-12;
}

If "theHour" is 0, then it is "12" am, no?
Mick
 
L

Lee

Otter said:
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).

It's tough to find because it's not a reasonable way to
measure time.

The length of "three months" can vary by up to three days,
depending on where that period happens to fall in the
calendar year.

If you want to measure time in months, you shouldn't try
to do so in precision greater than half a month.
 
O

Otter

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

It's not exactly what you want, but it's close.

Thanks for that.

Back when I first tried looking for a solution I found a countdown
timer which I used, then modified after the birth to start counting up
(i literally dont know anything about javascript but was able to
figure out enough to make the necessary changes). The only problem is
that it only counts up in terms of days.

I've since replaced the code with a much more streamlined day counter.

I've looked high and low for a javascript counter which can break down
to years/month/days since an event happened but I have yet to find
one. I am assuming now that it can't be done otherwise I'm sure I
would have come across one by now. Found lots of unanswered requests
for the same by others.

I HAVE seen one in cgi-bin but I know even less about that, and I
don't think my service provider allows their use anyway.
http://www.muquit.com/muquit/software/Count/Count2.6/Count.html

An example of what I'm trying to accomplish appears as the last item
here:
http://www.muquit.com/muquit/software/Count/Count2.6/Count2.6/examples.html

Maybe I'll have to start investigating this option.

-Otter
 
D

Dr John Stockton

JRS: In article <BD62B3FF.CE2B%[email protected]>, dated Mon, 6
Sep 2004 23:38:44, seen in Ian Sedwell
Yes I did.

You would have done better to read, with care, the newsgroup FAQ
instead.

Why should we expect the Americans to have an inferior intelligence?

Familiarity and intelligence are different concepts. President Bush may
or may not be of similar intelligence to President Putin; but he is
undoubtedly far less familiar with the Russian language. Pres.P is
probably less familiar with the New York Subways - though, given their
backgrounds, one should not be too sure of that.


It works very well.

Perhaps what it should give and what you think it should give are not
the same. I don't think that it gives what I think that it should give.

The code would not be needed if the 24-hour clock was used.

H12 = LZ(1+(H24+11)%12)+ [' am', ' pm'][+(H24>11)]
 
L

Lasse Reichstein Nielsen

Mick White said:
function showTheHour (theHour){
return theHour==0?12:theHour<13?theHour:theHour-12;
}

Then you could also do:

return ((theHour - 1) % 12) + 1;

which is shorter, although not necessarily faster :)

(Please trim your quotes)
/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 7 Sep 2004
19:19:49, seen in Lasse Reichstein Nielsen
Then you could also do:

return ((theHour - 1) % 12) + 1;

which is shorter, although not necessarily faster :)

Yields 0 1 2 12 1 2 11.

Use ((theHour + 11) % 12) + 1;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top