Last active
December 15, 2015 20:09
-
-
Save krhoyt/5316368 to your computer and use it in GitHub Desktop.
Returns the number years, months, days and minutes that have elapsed since a given date. Designed for displaying my daughters age on her web site.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MILLIS_DAY = 24 * 60 * 60 * 1000; | |
var MILLIS_HOUR = 60 * 60 * 1000; | |
var MILLIS_MINUTE = 60 * 1000; | |
var MILLIS_MONTH = 30 * 24 * 60 * 60 * 1000; | |
var MILLIS_YEAR = 31557600000; | |
function getAge( birthday ) | |
{ | |
var days = null; | |
var difference = null; | |
var minutes = null; | |
var months = null; | |
var result = null; | |
var today = null; | |
var years = null; | |
result = 'I am '; | |
today = new Date(); | |
difference = today.getTime() - birthday.getTime(); | |
years = Math.floor( difference / MILLIS_YEAR ); | |
difference = difference - ( years * MILLIS_YEAR ); | |
if( years == 1 ) | |
{ | |
result = result + years + ' year, '; | |
} else { | |
result = result + years + ' years, '; | |
} | |
months = Math.floor( difference / MILLIS_MONTH ); | |
difference = difference - ( months * MILLIS_MONTH ); | |
if( months == 1 ) | |
{ | |
result = result + months + ' month, '; | |
} else { | |
result = result + months + ' months, '; | |
} | |
days = Math.floor( difference / MILLIS_DAY ); | |
difference = difference - ( days * MILLIS_DAY ); | |
if( days == 1 ) | |
{ | |
result = result + days + ' day, '; | |
} else { | |
result = result + days + ' days, '; | |
} | |
hours = Math.floor( difference / MILLIS_HOUR ); | |
difference = difference - ( hours * MILLIS_HOUR ); | |
if( hours == 1 ) | |
{ | |
result = result + hours + ' hour, '; | |
} else { | |
result = result + hours + ' hours, '; | |
} | |
minutes = Math.floor( difference / MILLIS_MINUTE ); | |
if( minutes == 1 ) | |
{ | |
result = result + ' and ' + minutes + ' minute old.'; | |
} else { | |
result = result + ' and ' + minutes + ' minutes old.'; | |
} | |
return result; | |
} | |
document.writeln( getAge( new Date( 2004, 5, 4, 0, 58 ) ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment