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.
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.getDate());
}
function addMth(a) {
return new Date(check2k(a.getYear()),1*a.getMonth()+1,a.getDate());
}
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>