You are here: irt.org | FAQ | JavaScript | Date | Q99 [ previous next ]
<script language="JavaScript"><!--
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
function timeTillDate(whenDay,whenMonth,whenYear) {
var now = new Date();
var thisDay = now.getDate(), thisMonth = now.getMonth() + 1, thisYear = y2k(now.getYear());
var yearsDifference = whenYear - thisYear, monthsDifference = 0, daysDifference = 0, string = '';
if (whenMonth >= thisMonth) monthsDifference = whenMonth - thisMonth;
else { yearsDifference--; monthsDifference = whenMonth + 12 - thisMonth; }
if (whenDay >= thisDay)daysDifference = whenDay - thisDay;
else {
if (monthsDifference > 0) monthsDifference--;
else { yearsDifference--; monthsDifference+=11; }
daysDifference = whenDay + 31 - thisDay;
}
if (yearsDifference < 0) return '';
if ((yearsDifference == 0) && (monthsDifference == 0) && (daysDifference == 0))
return '';
if (yearsDifference > 0) {
string = yearsDifference + ' year';
if (yearsDifference > 1) string += 's';
string += ' ';
}
if (monthsDifference > 0) {
string += monthsDifference + ' month';
if (monthsDifference > 1) string += 's';
string += ' ';
}
if (daysDifference > 0) {
string += daysDifference + ' day';
if (daysDifference > 1) string += 's';
string += ' ';
}
var difference = Date.UTC(y2k(now.getYear()),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds()) -
Date.UTC(y2k(now.getYear()),now.getMonth(),now.getDate(),0,0,0);
difference = 1000*60*60*24 - difference;
var hoursDifference = Math.floor(difference/1000/60/60);
difference = difference - hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference = difference - minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);
if (hoursDifference > 0) {
string += hoursDifference + ' hour';
if (hoursDifference > 1) string +='s';
string += ' ';
}
if (minutesDifference > 0) {
string += minutesDifference + ' minute';
if (minutesDifference > 1) string +='s';
string += ' ';
}
if (secondsDifference > 0) {
string += secondsDifference + ' second';
if (secondsDifference > 1) string +='s';
string += ' ';
}
return string;
}
document.write(timeTillDate(31,12,1999));
//--></script>