473,372 Members | 1,040 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

counting years between two dates

Hello all

Problem like in subject. There is no problem when I want to count days
between two dates. Problem is when I want to count years becouse of
leap years.

For ex.

between
2002-11-19 2003-11-19
365 days = 1 year

between
2003-11-19 2004-11-19
366 days = 1 year (leap)

Thanks
Bambero
Jul 23 '05 #1
7 12793
> Problem like in subject. There is no problem when I want to count days
between two dates. Problem is when I want to count years becouse of
leap years.

For ex.

between
2002-11-19 2003-11-19
365 days = 1 year

between
2003-11-19 2004-11-19
366 days = 1 year (leap)


I am not familiar enough with javascript to be able to give you the correct
answer, but I can tell you that you will need to use some sort of date
object.

The date object should have a way of finding the date as it is represented
in seconds since the epoch.

So, you would create two date objects, find their time in seconds since
the epoch, and convert this into a number of days.

In fact I just googled for "javascript date" and the first result has the
answer.

// UNTESTED
var date1 = new Date(yr_num, mo_num, day_num);
var date2 = new Date(yr_num2, mo_num2, day_num2);

var date1_in_seconds = date1.parse();
var date2_in_seconds = date2.parse();

var difference = date_2_in_seconds - date_1_in_seconds
// above is assuming date2 is more recent than date1

//now difference is the number of seconds between the two dates so...
var difference in years = int(difference / 140400)
//this would be the number of days in between the two dates...
Jul 23 '05 #2
Lee
Bambero said:

Hello all

Problem like in subject. There is no problem when I want to count days
between two dates. Problem is when I want to count years becouse of
leap years.


http://www.merlyn.demon.co.uk/js-date1.htm#DY

Jul 23 '05 #3
Bambero wrote:
Hello all

Problem like in subject. There is no problem when I want to count days
between two dates. Problem is when I want to count years becouse of
leap years.


I would guess you are having trouble with months too.

The best way is to convert to date objects, then deal with those. When
measuring days, months and years between two dates it is simpest to
add one year/month/day at a time until the earlier date gets to the
later date. The following script doesn't care whether the lower date
is entered first or last, it sorts them out anyway.

The following assumes you have done all that is required to validate
that dates are entered as yyyy-mm-dd. It is tested in Safari, but
should work elsewhere.

Have fun, Rob.
<html><head><title>Date fun</title>

<script type="text/javascript">
function check2k(a) {
return (a<1900)?a -= -1900:a;
}

function addYr(a) {
return new Date(check2k(1*a.getYear()+1),a.getMonth(),a.getDa te());
}

function addMth(a) {
return new Date(check2k(a.getYear()),1*a.getMonth()+1,a.getDa te());
}

function addDay(a) {
return new Date(check2k(a.getYear()),a.getMonth(),1*a.getDate ()+1);
}

function doDate(in1,in2) {
var x = in1.split('-'),
y = in2.split('-'),
yrCount = 0,
mthCount = 0,
dayCount = 0;

// Convert to dates
var date0 = new Date(x[0],x[1]-1,x[2]);
var date1 = new Date(y[0],y[1]-1,y[2]);

// Make the lower one date0
if (date0 > date1) {
date0 = date1;
date1 = new Date(x[0],x[1]-1,x[2]);
}

// Add years to date0 until after date1
while (addYr(date0) <= date1) {
date0 = addYr(date0);
yrCount++;
}

// Add months to date0 until after date1
while (addMth(date0) <= date1) {
date0 = addMth(date0);
mthCount++;
}

// Add days to date0 until after date1
while (addDay(date0) <= date1) {
date0 = addDay(date0);
dayCount++
}

alert('Years: ' + yrCount
+ '\nMonths: ' + mthCount
+ '\nDays: ' + dayCount
);
}
</script>

</head>
<body>

<form action="">
<input type="text" name="y1" width="100px"
value="2003-12-23">Year 1<br>
<input type="text" name="y2" width="100px"
value="2002-12-28">Year 2<br>
<input type="button" value="Calc years" onclick="
doDate(this.form.y1.value, this.form.y2.value);
"><br>
</form>

</body></html>
Jul 23 '05 #4
RobG wrote:
[...]
The following assumes you have done all that is required to validate
that dates are entered as yyyy-mm-dd. It is tested in Safari, but
should work elsewhere.

[...]

Forgot to mention, you also need to ensure dates are after 1900.

Cheers, Rob.
Jul 23 '05 #5
JRS: In article <99und.330977$a85.63670@fed1read04>, dated Fri, 19 Nov
2004 14:08:29, seen in news:comp.lang.javascript, news.west.cox.net
<se*********@cox.net> posted :
Problem like in subject.
NEVER rely on the Subject line.
There is no problem when I want to count days
between two dates. Problem is when I want to count years becouse of
leap years.

For ex.

Don't use abbreviations in languages which are not your own, unless you
have good reason for believing that they exist and you know their exact
meaning.

between
2002-11-19 2003-11-19
365 days = 1 year
Actually there are 364 days between those dates; it is the difference
which is 365.
between
2003-11-19 2004-11-19
366 days = 1 year (leap)


I am not familiar enough with javascript to be able to give you the correct
answer,


Better, then, to leave it to those who do.
but I can tell you that you will need to use some sort of date
object.
/Non sequitur/.

The date object should have a way of finding the date as it is represented
in seconds since the epoch.
It is not represented in seconds.

So, you would create two date objects, find their time in seconds since
the epoch, and convert this into a number of days.
One does not *need* two objects; it is possible to use one twice; or,
for speed, not to use a date object at all. The best solution depends
on the format in which the date is initially available. For example, if
the dates are ISO 8601 YYYYMMDD strings, one can subtract them, divide
by 1e4, and truncate.
In fact I just googled for "javascript date" and the first result has the
answer.
Indiscriminate Googling for javascript is a *reliable* method of finding
bad answers. A good answer could have been found by studying the FAQ of
this newsgroup.
// UNTESTED
Untested code, even when written by an expert, is almost reliably wrong.
var date1 = new Date(yr_num, mo_num, day_num);
var date2 = new Date(yr_num2, mo_num2, day_num2);

var date1_in_seconds = date1.parse();
var date2_in_seconds = date2.parse();
The date object does not AFAIK ever have a native parse method.
var difference = date_2_in_seconds - date_1_in_seconds
// above is assuming date2 is more recent than date1

//now difference is the number of seconds between the two dates so...
var difference in years = int(difference / 140400)
//this would be the number of days in between the two dates...


140400 seconds is one day fifteen hours; that is less than a year. As
the OP evidently realises, the number of seconds in a year is not
constant.

Post only tested solutions, on topics that you have a good understanding
of.
A further problem, for methods based on seconds, would be shown (to
many users) for the differences of some pairs of dates of the form
YYYY-10-28.
For the OP :

X = (Y2-Y1) - (M2*100+D2 < M1*100+D1) // for Y M D numbers

A1 = Y1.split(/\D+/) ; A2 = Y2.split(/\D+/)
X = (A2[0]-A1[0]) - (A2[1]*100 + +A2[2] < A1[1]*100 + +A1[2])
// for inputs YYYY-MM-DD, YYYY/MM/DD, etc.

Lightly tested. See below.

--
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.
Jul 23 '05 #6
Dr John Stockton wrote:
[...]
A further problem, for methods based on seconds, would be shown (to
many users) for the differences of some pairs of dates of the form
YYYY-10-28.


What is the accepted value for 2004-02-29 + 1 year? Is it 2005-03-01
as the JavaScript date function in every browser I tested returns, or
is it 2005-02-28 as logic might have it (if my logic is consistent with
popular opinion...)

Cheers, Rob.
Jul 23 '05 #7
JRS: In article <41a07bdc$0$25762$5a62ac22@per-qv1-newsreader-
01.iinet.net.au>, dated Sun, 21 Nov 2004 21:27:24, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auau> posted :
Dr John Stockton wrote:
[...]
A further problem, for methods based on seconds, would be shown (to
many users) for the differences of some pairs of dates of the form
YYYY-10-28.


What is the accepted value for 2004-02-29 + 1 year? Is it 2005-03-01
as the JavaScript date function in every browser I tested returns, or
is it 2005-02-28 as logic might have it (if my logic is consistent with
popular opinion...)


Note that I wrote YYYY-10-28.

AFAICS, ECMA does not define (2004-02-29 + 1 year) explicitly; but it is
probably implicitly defined as a consequence of the way that ECMA says
that set[Full]Year should work; and likewise for adding a month to dates
too late in the previous longer month.

Note that D = new Date("2003/01/31") ; D.setMonth(1) gives March
3rd, and that will not generally be acceptable.

IMHO, the accepted value, outside javascript, is "Don't know; get a
[signed] ruling from the Boss"; either Feb 28 xor Mar 1 should be
considered acceptable. Somewhere on my site, IIRC, there is code to
handle the case of incrementing by an integer number of months from a
day-of-month not available at the destination ... js-date0.htm#MC .
Those who can read German might like to look at
<URL:http://www.merlyn.demon.co.uk/zel-82px.htm>
and its neighbours; those knowing Latin see 83 not 82.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #8

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

Similar topics

6
by: Elbert Lev | last post by:
Please correct me if I'm wrong. Python (as I understand) uses reference counting to determine when to delete the object. As soon as the object goes out of the scope it is deleted. Python does...
6
by: edwardfredriks | last post by:
I'm looking for a script that, instead of counting down, can "count up" from a given date. So the output should be something like "(xx) days since (date/event)" or "(date/event) was (xx) days ago"....
8
by: regrat | last post by:
It's possible create a javascript which counts all words in a webpage until the point in which I click with the mouse. Any suggests?
4
by: Alicia | last post by:
I am having a problem grouping by week. I am looking for the simpliest way of doing it in Microsoft Access. I have tried to use a pre-loaded calender, access did not like it at all. If there is...
6
by: carl.barrett | last post by:
Hi, I have a continuous form based on a query ( I will also be creating a report based on the same query). There are 2 fields: Date Obtained and Date Of Expiry I want a further 3 columns...
14
by: jpr | last post by:
Friends, I have a form with four fields, date1, date2, date3 and date4. All these have all a mm/dd/yyyy format and have their source to a table. I need to add an unbound control (I will name...
2
by: Jannick | last post by:
Help..please! I'm a rookie in terms of VB, but I'm desperately trying to make Access count the number of days between two dates and then subtract the weekends. Can anyone tell me what is wrong...
4
by: jamesyreid | last post by:
Hi, 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. Does anyone have a snippet of JavaScript code I could borrow...
2
by: ichew | last post by:
I have two dates - Date Joined and Actual Last Day. How do I find the YIS in for format of Years and Month from these two dates. Eg, Date Joined: 28/06/1971 and Actual Last Day: 24/01/2007, then...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.