Friendly Date Ranges
by Vadim Costin
JavaScript
//jshint esversion: 6
function makeFriendlyDates(arr) {
const monthNames = [
'January', 'February', 'March',
'April', 'May', 'June', 'July',
'August', 'September', 'October',
'November', 'December'
];
const firstDate = new Date(arr[0]);
const secondDate = new Date(arr[1]);
const moreThanOneYear = secondDate.getTime() - firstDate.getTime() >= 3.1536e+10;
const sameMonth = firstDate.getMonth() === secondDate.getMonth();
const isNextYear = firstDate.getFullYear() + 1 === secondDate.getFullYear();
const isSameYear = firstDate.getFullYear() === secondDate.getFullYear();
let firsDateOut = '';
let secondDateOut = '';
firsDateOut += monthNames[firstDate.getMonth()];
firsDateOut += ' ' + getGetOrdinal(firstDate.getDate());
if(secondDate.getTime() === firstDate.getTime()){
firsDateOut += ', ' + firstDate.getFullYear();
return [firsDateOut];
}
if(!moreThanOneYear && isSameYear && sameMonth){
secondDateOut += getGetOrdinal(secondDate.getDate());
}
else if(!moreThanOneYear && isNextYear && !sameMonth){
secondDateOut += monthNames[secondDate.getMonth()];
secondDateOut += ' ' + getGetOrdinal(secondDate.getDate());
}
else if(!moreThanOneYear){
firsDateOut += ', ' + firstDate.getFullYear();
secondDateOut += monthNames[secondDate.getMonth()];
secondDateOut += ' ' + getGetOrdinal(secondDate.getDate());
}
else {
firsDateOut += ', ' + firstDate.getFullYear();
secondDateOut += monthNames[secondDate.getMonth()];
secondDateOut += ' ' + getGetOrdinal(secondDate.getDate());
secondDateOut += ', ' + secondDate.getFullYear();
}
return [firsDateOut, secondDateOut];
}
function getGetOrdinal(n) {
const s = ['th','st','nd','rd'];
const v = n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
//const results = makeFriendlyDates(['2016-07-01', '2016-07-04']);
const results = makeFriendlyDates(["2016-12-01", "2017-02-03"]); // ["December...