2018-07-14 00:20:14 +02:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// P R O G R A M
|
|
|
|
|
2019-07-10 19:34:19 +02:00
|
|
|
const relativeDate = (() => {
|
2018-07-14 00:20:14 +02:00
|
|
|
const SECOND = 1000;
|
|
|
|
const MINUTE = 60 * SECOND;
|
|
|
|
const HOUR = 60 * MINUTE;
|
|
|
|
const DAY = 24 * HOUR;
|
|
|
|
const WEEK = 7 * DAY;
|
|
|
|
const YEAR = DAY * 365;
|
|
|
|
const MONTH = YEAR / 12;
|
|
|
|
|
|
|
|
const formats = [
|
2019-07-12 00:09:36 +02:00
|
|
|
[0.7 * MINUTE, "just now"],
|
|
|
|
[1.5 * MINUTE, "a minute ago"],
|
|
|
|
[60 * MINUTE, "minutes ago", MINUTE],
|
|
|
|
[1.5 * HOUR, "an hour ago"],
|
|
|
|
[DAY, "hours ago", HOUR],
|
|
|
|
[2 * DAY, "yesterday"],
|
|
|
|
[7 * DAY, "days ago", DAY],
|
|
|
|
[1.5 * WEEK, "a week ago"],
|
|
|
|
[MONTH, "weeks ago", WEEK],
|
|
|
|
[1.5 * MONTH, "a month ago"],
|
|
|
|
[YEAR, "months ago", MONTH],
|
|
|
|
[1.5 * YEAR, "a year ago"],
|
|
|
|
[Number.MAX_VALUE, "years ago", YEAR]
|
2018-07-14 00:20:14 +02:00
|
|
|
];
|
|
|
|
|
|
|
|
function relativeDate(input, reference) {
|
2019-07-12 00:09:36 +02:00
|
|
|
!reference && (reference = (new Date()).getTime());
|
2018-07-14 00:20:14 +02:00
|
|
|
reference instanceof Date && (reference = reference.getTime());
|
|
|
|
input instanceof Date && (input = input.getTime());
|
|
|
|
|
|
|
|
const delta = reference - input;
|
|
|
|
const len = formats.length;
|
|
|
|
|
|
|
|
for (let i = -1; ++i < len;) {
|
|
|
|
const format = formats[i];
|
|
|
|
|
2019-07-12 00:09:36 +02:00
|
|
|
if (delta < format[0])
|
2018-07-14 00:20:14 +02:00
|
|
|
return format[2] === undefined ? format[1] : Math.round(delta / format[2]) + " " + format[1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return relativeDate;
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// E X P O R T
|
|
|
|
|
2019-07-10 19:34:19 +02:00
|
|
|
if (typeof module !== "undefined" && module.exports)
|
2018-07-14 00:20:14 +02:00
|
|
|
module.exports = exports = relativeDate;
|