Created
May 16, 2016 14:27
-
-
Save lemmon/d27c2d4a783b1cf72d1d1cc243458d56 to your computer and use it in GitHub Desktop.
Calculates difference in years, months, and days between today and a date in past. Takes one string parameter -- date in YYYY-MM-DD format.
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
function dateDiff(date) { | |
date = date.split('-'); | |
var today = new Date(); | |
var year = today.getFullYear(); | |
var month = today.getMonth() + 1; | |
var day = today.getDate(); | |
var yy = parseInt(date[0]); | |
var mm = parseInt(date[1]); | |
var dd = parseInt(date[2]); | |
var years, months, days; | |
// months | |
months = month - mm; | |
if (day < dd) { | |
months = months - 1; | |
} | |
// years | |
years = year - yy; | |
if (month * 100 + day < mm * 100 + dd) { | |
years = years - 1; | |
months = months + 12; | |
} | |
// days | |
days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000)); | |
// | |
return {years: years, months: months, days: days}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mark