Skip to content

Instantly share code, notes, and snippets.

@le717
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le717/11162997 to your computer and use it in GitHub Desktop.
Save le717/11162997 to your computer and use it in GitHub Desktop.
From my tutorial "JS - Calculate your age" (http://wp.me/p1V5ge-1tM)
/* 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