-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfriendly-date-ranges.js
75 lines (60 loc) · 2.16 KB
/
friendly-date-ranges.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function ordinal(d) {
var s = ["th","st","nd","rd"],
v = d % 100;
return d+(s[(v-20)%10]||s[v]||s[0]);
}
function dateDifferenceInDays(date1, date2) {
return Math.floor((date2 - date1) / (1000*60*60*24));
}
function dateDifferenceIsAYearOrMore(date1, date2) {
return dateDifferenceInDays(date1, date2) >= 365;
}
function datesHaveTheSameMonth(date1, date2) {
return date1.getMonth() === date2.getMonth();
}
function datesHaveTheSameYear(date1, date2) {
return date1.getFullYear() === date2.getFullYear();
}
function datesAreEqual(date1, date2) {
if (date1.getDate() !== date2.getDate()) {
return false;
}
if (date1.getMonth() !== date2.getMonth()) {
return false;
}
if (date1.getFullYear() !== date2.getFullYear()) {
return false;
}
return true;
}
function makeFriendlyDates(arr) {
const dateArr = arr.map(dateStr => new Date(dateStr));
const locale = "en-uk";
const currentYear = 2016; // (new Date().getFullYear())
let from, to;
[from, to] = dateArr;
if (datesAreEqual(from, to)) {
return [`${from.toLocaleString(locale, { month: "long" })} ${ordinal(from.getDate())}, ${from.getFullYear()}`];
}
if (from.getFullYear() === to.getFullYear() && from.getMonth() === to.getMonth()) {
return [`${from.toLocaleString(locale, { month: "long" })} ${ordinal(from.getDate())}`, `${ordinal(to.getDate())}`];
}
if (from.getFullYear() === currentYear && !dateDifferenceIsAYearOrMore(from, to)) {
return [
`${from.toLocaleString(locale, { month: "long" })} ${ordinal(from.getDate())}`,
`${to.toLocaleString(locale, { month: "long" })} ${ordinal(to.getDate())}`
];
}
if (from.getFullYear() !== currentYear && !dateDifferenceIsAYearOrMore(from, to)) {
return [
`${from.toLocaleString(locale, { month: "long" })} ${ordinal(from.getDate())}, ${from.getFullYear()}`,
`${to.toLocaleString(locale, { month: "long" })} ${ordinal(to.getDate())}`
];
}
if (dateDifferenceIsAYearOrMore(from, to)) {
return [
`${from.toLocaleString(locale, { month: "long" })} ${ordinal(from.getDate())}, ${from.getFullYear()}`,
`${to.toLocaleString(locale, { month: "long" })} ${ordinal(to.getDate())}, ${to.getFullYear()}`
];
}
}