473,769 Members | 4,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4415
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


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

Read the faq:

<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.
(Please change the x'es to dots in my emailaddress,
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';}
alert(t);

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';}
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.

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


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]
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';}
alert(t);


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';}
alert(t);


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.

Thanx in advance.
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
like to look at it, check the HEEEELP section for download
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.

Similar topics

13
3932
by: David Gray | last post by:
Greetings all, Quick newbie type question: I would like to be able to trap non-numerical data entered into a textbox via CTRL+C and/or Shift+Insert. I realise that this data can be validated using the TEXTn_validate event but I would like to stop the user before it gets that far.
4
10114
by: Manny Chohan | last post by:
Hi Can anyone tell me how i can calculate yesterday date using asp? Thanks manny
5
6738
by: SimonC | last post by:
Help needed for a Javascript beginner. As above in the subject... i need a javascript to run this, but not in the form of a web-page. I want to calculate it between 2 fields in a database that i have extracted into a report writer. Look forward to hearing.. Cheers... SimonC
1
21369
by: bradleyc | last post by:
How would you calculate the difference between two dates?
2
3650
by: Steve | last post by:
Hi all How would I find out the average date when given a bunch of dates? For example, I want to find the average length in time from the following dates: ---------------------------------------------------- Start Date End Date 01/01/2004 12:50pm 02/01/2004 18:40pm 02/01/2004 13:40pm 02/01/2004 13:57pm 02/01/2004 14:30pm 02/01/2004 19:50pm
5
7850
by: infobescom | last post by:
Hi I am wrking on a application where i need to calculate the difference between two dates .. here is the formula i am using ........ Public Function GetNumberOfWorkDays(sStartDate, sEndDate) Dim iWorkDays
8
17579
by: helpless | last post by:
Access 2003 - I am trying to calculate the difference between a specific date 5/1/2007 (not in a data field) and other dates that ARE in a field called Birth Date. I am trying to have it fill into an Age field (in years only) by comparing the date above to the Birth Date field. I have tried this and it doesn't work: =DateDiff("yyyy", , ) Displays the variance in years between the values of the Birthday1 and Birthday2 fields. (from Access...
7
54943
by: walt | last post by:
Hello, I have been trying to calculate the difference between two date and display the difference in hours and minutes (HH:MM). I can't get it calculate properly and I can't hours and minutes to display. I tried "results=enddate-startdate" dates have month, day, year,and time of day. After this calculation I end up with no results. Any help would be appreciated. Walt
4
50192
by: lenygold via DBMonster.com | last post by:
I found this example in MYSQL: create table events ( id integer not null primary key , datetime_start datetime not null , datetime_end datetime not null ); insert into events values ( 1, '2006-09-09 14:00', '2006-09-09 16:00' ) ,( 2, '2006-09-10 09:00', '2006-09-10 17:00' ) ,( 3, '2006-09-11 13:30', '2006-09-11 14:45' )
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6673
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3959
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3562
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.