Last active
August 22, 2017 22:53
-
-
Save imthenachoman/4067ae4fd0402a4088b55a8856013b5b to your computer and use it in GitHub Desktop.
javascript pretty date difference with year, month, day
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 nachoDateDiff(startDate, endDate) | |
{ | |
// if start date is past end date stop | |
if(startDate > endDate) return null; | |
// calc the various start/end dates | |
var sy = startDate.getFullYear(), | |
ey = endDate.getFullYear(), | |
sm = startDate.getMonth(), | |
em = endDate.getMonth(), | |
sd = startDate.getDate(), | |
ed = endDate.getDate(); | |
// find the difference | |
var years = ey - sy; | |
var months = em - sm; | |
var days = ed - sd; | |
// if month is negative we need to go back one year and find the new months | |
if(months < 0) | |
{ | |
years--; | |
months += 12; | |
} | |
// if days is negative we need to go back one month and find the right days | |
if(days < 0) | |
{ | |
months--; | |
days += (new Date(ey, em + 1, 0).getDate()); | |
} | |
// return | |
return [years, months, days]; | |
} | |
// example | |
nachoDateDiff(new Date(2016,5,15), new Date(2019,3,10)); // [2, 9, 25] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment