Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:51
Show Gist options
  • Save rfprod/82731711e17cc9f987bb to your computer and use it in GitHub Desktop.
Save rfprod/82731711e17cc9f987bb to your computer and use it in GitHub Desktop.
Friendly Date
function friendlyDate(dateArr) {
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var firstDate = [], secondDate = [];
dateArr.reduce(function(previousValue,currentValue){
firstDate = previousValue.split("-");
secondDate = currentValue.split("-");
});
dateArr = ["",""]; // init output
var mnth = [firstDate[1],secondDate[1]];
var d = [firstDate[2],secondDate[2]];
var yr = [firstDate[0],secondDate[0]];
// month
if (mnth[0] == mnth[1] && yr[0] == yr[1]){
if (mnth[0][0] == "0") {mnth[0] = mnth[0].substr(1,1);}
dateArr[0] += month[mnth[0]-1];
}else{
if (mnth[0][0] == "0") {mnth[0] = mnth[0].substr(1,1);}
if (mnth[1][0] == "0") {mnth[1] = mnth[1].substr(1,1);}
dateArr[0] += month[mnth[0]-1];
dateArr[1] += month[mnth[1]-1];
}
// day
if (d[0][0] == "0") {d[0] = d[0].substr(1,1);}
if (d[1][0] == "0") {d[1] = d[1].substr(1,1);}
for (var i=0;i<d.length;i++){
switch (d[i][d[i].length-1]){
case "1": d[i] += "st"; break;
case "2": d[i] += "nd"; break;
case "3": d[i] += "rd"; break;
default: d[i] += "th";
}
if (dateArr[i].length > 0){dateArr[i] += " "+d[i];}else{dateArr[i] += d[i];}
}
// year
if (yr[0] == yr[1] && parseInt(mnth[0]) == parseInt(mnth[1]) && d[0] == d[1]){
dateArr[0] += ", "+yr[0];
dateArr.pop();
}else if (yr[0] == yr[1] || (yr[1] - yr[0] > 0 && yr[1] - yr[0] < 2 && mnth[0] == 12)){
//nothing
}else{
dateArr[0] += ", "+yr[0];
dateArr[1] += ", "+yr[1];
}
//return JSON.stringify(firstDate)+" ~ "+JSON.stringify(secondDate);
//return JSON.stringify(dateArr);
return dateArr;
}
//friendlyDate(['2016-07-01', '2016-07-04']);
//friendlyDate(["2016-12-01", "2018-02-03"]);
//friendlyDate(["2018-01-01", "2018-01-01"]);
friendlyDate(["2022-09-05", "2023-09-04"]);

Friendly Date Ranges

Converts two dates into a more friendly date range that could be presented to a user. It does not show any redundant information in the date range. If the year and month are the same then only the day range should be displayed. If the starting year is the current year, and the ending year can be inferred by the reader, the year should be omitted. Input date format is YYYY-MM-DD

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment