Skip to content

Instantly share code, notes, and snippets.

@teisman
Created February 28, 2016 17:08
Show Gist options
  • Save teisman/6a16bfd2d8aa7a259937 to your computer and use it in GitHub Desktop.
Save teisman/6a16bfd2d8aa7a259937 to your computer and use it in GitHub Desktop.
function friendly(arr) {
var now = new Date();
var fromDate = new Date(Date.parse(arr[0]));
var toDate = new Date(Date.parse(arr[1]));
var ord = [];
if (sameYear(fromDate, now) && withinOneYear(fromDate, toDate)) {
// Year should not be displayed at first date
ord[0] = monthName(fromDate) + " " + nth(fromDate);
} else {
// All should be displayed at first date
ord[0] = monthName(fromDate) + " " + nth(fromDate) + ", " + fromDate.getFullYear();
}
if (sameDay(fromDate, toDate)) {
return ord;
}
if (sameMonth(fromDate, toDate)) {
// Year and month should not be displayed at second date
ord[1] = nth(toDate);
} else if (withinOneYear(fromDate, toDate)) {
// Month should not be displayed at second date
ord[1] = monthName(toDate) + " " + nth(toDate);
} else {
// All information should be displayed at second date
ord[1] = monthName(toDate) + " " + nth(toDate) + ", " + toDate.getFullYear();
}
return ord;
}
function sameDay(d1, d2) {
// return ture if days, months and years match
return (d1.getDate() === d2.getDate()) && sameMonth(d1, d2);
}
function sameMonth(d1, d2) {
// return true if months and years match
return (d1.getMonth() === d2.getMonth()) && sameYear(d1, d2);
}
function sameYear(d1, d2) {
// return true if years match
return d1.getYear() === d2.getYear();
}
function nth(d) {
d = d.getDate();
s = String(d);
if(d>3 && d<21) return s + 'th';
switch (d % 10) {
case 1: return s + "st";
case 2: return s + "nd";
case 3: return s + "rd";
default: return s + "th";
}
}
function monthName(d) {
return "January,February,March,April,May,June,July,August,September,October,November,December".split(",")[d.getMonth()];
}
function withinOneYear(d1, d2) {
// return true if less than one year apart
// NOTE: function doesn't work for leap years
tmp = new Date(d2.getTime());
tmp.setMonth(tmp.getMonth() - 12);
return (d1 > tmp);
}
friendly(["2022-09-05", "2023-09-05"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment