Skip to content

Instantly share code, notes, and snippets.

@jampola
Created November 1, 2016 06:30
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 jampola/c5dcbadf6488fec3ae044666ef02d159 to your computer and use it in GitHub Desktop.
Save jampola/c5dcbadf6488fec3ae044666ef02d159 to your computer and use it in GitHub Desktop.
Friendly Date Ranges (FreeCodeCamp)
function makeFriendlyDates(arr) {
dateArr = [];
months = {
'01':'January','02':'February','03':'March',
'04':'April','05':'May','06':'June',
'07':'July','08':'August','09':'September',
'10':'October','11':'November','12':'December'
};
function returnDay(day){
var intDay = parseInt(day);
if(intDay == 1 || intDay == 21 || intDay == 31){
return intDay+"st";
}
else if (intDay == 2 || intDay == 22){
return intDay+"nd";
}
else if(intDay == 3 || intDay == 23){
return intDay+"rd";
}
else {
return intDay+"th";
}
}
var curYear = new Date().getFullYear();
var monthFrom = months[arr[0].substr(5,2)];
var monthTo = months[arr[1].substr(5,2)];
var yearFrom = arr[0].substr(0,4);
var yearTo = arr[1].substr(0,4);
var dayFrom = returnDay(arr[0].substr(-2));
var dayTo = returnDay(arr[1].substr(-2));
var dateFrom = new Date(arr[0]);
var dateTo = new Date(arr[1]);
// 1 year = 31449600000
var difference = dateTo.getTime() - dateFrom.getTime();
if(difference <= 31449600000 && yearTo != curYear && yearTo != yearFrom && yearFrom != curYear){
// console.log("within a year");
dateArr.push(monthFrom + " " + dayFrom + ", " + yearFrom, monthTo + " " + dayTo);
}
else if(difference <= 31449600000 && yearTo != curYear && yearTo != yearFrom && yearFrom == curYear){
// console.log("within a year");
dateArr.push(monthFrom + " " + dayFrom, monthTo + " " + dayTo);
}
// if current year, same month
// eg: 2016-07-01 - 2016-07-04 ("July 1st", "4th")
else if(curYear == yearFrom && monthFrom == monthTo){
dateArr.push(monthFrom + " " + dayFrom, dayTo);
}
// if same year different months
else if(yearFrom == yearTo && monthFrom != monthTo){
dateArr.push(monthFrom + " " + dayFrom + ", " + yearFrom, monthTo + " " + dayTo);
}
// if same year, date and month
else if (yearFrom == yearTo && monthFrom == monthTo && dayFrom == dayTo){
dateArr.push(monthFrom + " " + dayFrom + ", " + yearFrom);
}
// push the rest. woop.
else {
dateArr.push(monthFrom + " " + dayFrom + ", " + yearFrom, monthTo + " " + dayTo + ", " + yearTo);
}
return dateArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment