Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

32 years 8 months 24 days

You are here: irt.org | Articles | JavaScript | Date and Time | 32 years 8 months 24 days

Published on: Saturday 11th October 1997 By: Martin Webb

Introduction

This article will describe how to calculate the age in years, months and days of someone who supplies their birthdate.

It will use the date input routines described in the previous article Blind Date.

How old are you?

The following HowOld() function works out the difference between the two dates represented by day, month, year and thisDay, thisMonth, thisYear.

The HowOld() function relies on the first date being older than the second date.

It uses simple addition and subtraction to calculate the difference, using borrowing to borrow from yearsold and monthsold where month is greater than thisMonth and where day is greater then thisDay.

It returns an empty string if either the resulting yearsold is negative, or if yearsold, monthsold and daysold are all zero.

It finally returns a formatted string along the lines of: Age - 3 years 2 months 1 day

function HowOld(day,month,year,thisDay,thisMonth,thisYear) {
    var yearsold = thisYear - year, monthsold = 0, daysold = 0, string = '';

    if (thisMonth >= month) monthsold = thisMonth - month;
    else { yearsold--; monthsold = thisMonth + 12 - month; }

    if (thisDay >= day)daysold = thisDay - day;
    else {
        if (monthsold > 0) monthsold--;
        else { yearsold--; monthsold+=11; }
        daysold = thisDay + 31 - day;
    }

    if (yearsold < 0) return '';

    if ((yearsold == 0) && (monthsold == 0) && (daysold == 0))
        return '';

    if (yearsold > 0) {
        string = yearsold + ' year';
        if (yearsold > 1) string += 's';
        string += ' ';
    }

    if (monthsold > 0) {
        string += monthsold + ' month';
        if (monthsold > 1) string += 's';
        string += ' ';
    }

    if (daysold > 0) {
        string += daysold + ' day';
        if (daysold > 1) string += 's';
        string += ' ';
    }

    return '<P>Age - ' + string;
}

The HowOld() function can be utilised as follows:

document.write(HowOld(1,1,1900,4,10,1997));

Which when run produces:

Note, the above is not 100% accurate as it assumes that every month has 31 days.

Working Example

Why not try it out the frame version yourself. You may be older than you think!

Source Code

You can view the source code of the four components:

Feedback on '32 years 8 months 24 days'

View the profile on Martin Webb and the list of other Articles by Martin Webb.


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 21st December 2007. Maintained by: Martin Webb
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.