Created
May 24, 2016 12:58
-
-
Save amihaiemil/2fc5b7f30c3de9eb299ce74e0f62453d to your computer and use it in GitHub Desktop.
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
/** | |
* Get how much time has passed since refdate to date. | |
* @param date | |
* @param refdate | |
* @returns Json representing the time passed in with years, months and days. | |
* E.g. From 15.03.1994 to 24.05.2016 the time passed is | |
* 22years, 2 months and 9 days. | |
*/ | |
function timePassed(date, refdate) { | |
var year = date.getFullYear(); | |
var refYear = refdate.getFullYear(); | |
var month = date.getMonth(); | |
var refMonth = refdate.getMonth(); | |
var day = date.getDate(); | |
var refDay = refdate.getDate(); | |
//Calculate how many years have passed; | |
var years = refYear - year; | |
if(month > refMonth) { | |
years --; | |
} else if (month == refMonth) { | |
if(day > refDay) { | |
years --; | |
} | |
} | |
//Calculate how many months since last year turned | |
var months = 0;// = 12 - month - refMonth; | |
if(month < refMonth) { | |
months = refMonth - month; | |
if(day > refDay) { | |
months = months - 1; | |
} | |
} else { | |
if(month > refMonth) { | |
months = refMonth; | |
months = months + 11 - month; | |
if(day < refDay) { | |
months = months - 1; | |
} | |
} else { | |
if(day > refDay) { | |
months = 11; | |
} | |
} | |
} | |
//Calculate how many days since last month turned. | |
var days; | |
if(day == refDay) { | |
days = 0; | |
} else { | |
days = daysInMonth(refMonth, refYear) - day + 1; | |
} | |
var passed = new Object(); | |
passed.years = years; | |
passed.months = months; | |
passed.days = days; | |
return passed; | |
} | |
//Get number of days in a specific month of a specific year. | |
function daysInMonth(month,year) { | |
return new Date(year, month, 0).getDate(); | |
} | |
/** | |
* Compares two date jsons. | |
* @param date1 First date. | |
* @param date2 Second date. | |
* @returns 1 if date1 is bigger (older) than date2; | |
* 0 if the two ages are equal; | |
* -1 if date1 is smaller (younger) than date2; | |
*/ | |
function compareDates(date1, date2) { | |
if(date1.years > date2.years) { | |
return 1; | |
} else { | |
if(date1.years < date2.years) { | |
return -1; | |
} else {//years are equal, compare months. | |
if(date1.monghts > date2.months) { | |
return 1; | |
} else { | |
if(date1.monghts < date2.months) { | |
return -1; | |
} else {//months are equal, compare days. | |
if(date1.days > date2.days) { | |
return 1; | |
} else { | |
if(date1.days < date2.days) { | |
return -1; | |
} else {//years, months and days are all equal. | |
return 0; | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment