Skip to content

Instantly share code, notes, and snippets.

@imthenachoman
Last active August 22, 2017 22:53
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 imthenachoman/4067ae4fd0402a4088b55a8856013b5b to your computer and use it in GitHub Desktop.
Save imthenachoman/4067ae4fd0402a4088b55a8856013b5b to your computer and use it in GitHub Desktop.
javascript pretty date difference with year, month, day
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