Last active
January 11, 2022 09:13
-
-
Save xploshioOn/742af7bc0f7927fda4e2 to your computer and use it in GitHub Desktop.
get the duration between 2 dates and return a json with 3 values, years, months and days. like you want to obtain duration between 10/02/2013 to 25/05/2014 the function will return {years:1 months:3 days:15}
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 duration(since, until) { | |
//if first date is greater that the first, we fix the order | |
if (since > until) { | |
var temp = since; | |
since = until; | |
until = temp; | |
} | |
var years,months,days; | |
//Years | |
years = (until.getFullYear() - since.getFullYear()); | |
if (until.getMonth() == since.getMonth()){ | |
if (since.getDate() < (until.getDate()-1)) { | |
years += 1; | |
} | |
if(since.getDate()==until.getDate()){ | |
years+= 1; | |
} | |
} | |
if(since.getMonth() > until.getMonth()){ | |
years = (years - 1); | |
} | |
//Months | |
if(since.getDate() > until.getDate()){ | |
if(since.getMonth() > (until.getMonth()-1)){ | |
months = 11 - (since.getMonth() - until.getMonth()); | |
if (since.getMonth() == until.getMonth()){ | |
months = 11; | |
} | |
}else{ | |
months = until.getMonth() - since.getMonth() - 1; | |
} | |
}else{ | |
if(since.getMonth() > until.getMonth()){ | |
months = 12 - (until.getMonth() - since.getMonth()); | |
}else{ | |
months = until.getMonth() - since.getMonth(); | |
} | |
} | |
//Days | |
if(since.getDate() > (until.getDate()-1)){ | |
var days_pm = dayssInmonths(until.getMonth(until.getMonth()-1)); | |
days = days_pm - since.getDate() + until.getDate(); | |
if((since.getMonth() == until.getMonth()) & (since.getDate()==until.getDate())){ | |
days = 0; | |
} | |
}else{ | |
days = until.getDate() - since.getDate(); | |
} | |
return ({"years":years,"months":months,"days":days}); | |
} | |
function dayssInmonths(date){ | |
date = new Date(date); | |
return 32 - new Date(date.getFullYear(), date.getMonth(), 32).getDate(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it gets me NaN for years months and days ... whats wrong?