Last active
August 29, 2015 14:00
-
-
Save le717/11162997 to your computer and use it in GitHub Desktop.
From my tutorial "JS - Calculate your age" (http://wp.me/p1V5ge-1tM)
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
/* Calculate your age | |
* Created 2014-2015 Caleb Ely | |
* <http://CodeTriangle.me/> | |
* <https://wp.me/p1V5ge-1tM> | |
*/ | |
/** | |
* Calculate and display the year difference between two dates. | |
* @param {Object.<number>} date The starting date to calculate from. | |
* The object contains three numeric keys, year, month, and day. | |
* The year is expressed in four digits, e.g., 2015. | |
* @returns {Number} | |
*/ | |
function yearDifference(date) { | |
"use strict"; | |
var curDate = new Date(), | |
now = { | |
year: curDate.getUTCFullYear(), | |
// UTC month value is zero-based | |
month: curDate.getUTCMonth() + 1, | |
day: curDate.getUTCDate() | |
}, | |
diff = now.year % date.year; | |
// Do not update the date unless it is time | |
if (now.month < date.month || | |
now.month === date.month && now.day < date.day) { | |
diff -= 1; | |
} | |
return diff; | |
} | |
console.log(yearDifference({ year: 1995, month: 3, day: 13 })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment