www/lib/date.ts

81 lines
1.8 KiB
TypeScript
Raw Normal View History

const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
2022-04-28 01:55:18 +00:00
const ordSfx = ['','st','nd','rd','th'];
2022-10-05 03:41:59 +00:00
function toHumanReadableDate(date: Date | string, disable?: {year?: boolean, month?: boolean, day?: boolean}) {
const oDate = (typeof date === 'string')? new Date(date): date;
const year = oDate.getFullYear();
const month = months[oDate.getMonth()];
const day = oDate.getDate();
let sfx;
if (day >= 1 && day <= 3)
sfx = ordSfx[day];
else
sfx = ordSfx[4];
let out = !disable?.day ? `${day}${sfx}` : '';
out = !disable?.month ? `${out} ${month}` : out;
out = !disable?.year ? `${out} ${year}` : out;
return out;
}
function toRelativeDate(date: Date | string): string {
2022-04-28 01:55:18 +00:00
const oDate = (typeof date === 'string')? new Date(date): date;
const now = new Date();
2022-04-28 01:55:18 +00:00
const diff = now.getTime() - oDate.getTime();
let tdiff = Math.floor(diff/1000);
2022-10-05 03:41:59 +00:00
if (tdiff < 0) {
return toHumanReadableDate(oDate);
}
if (tdiff < 60) {
return `${tdiff} seconds ago`;
}
tdiff = Math.floor(tdiff/60);
if (tdiff < 60) {
return `${tdiff} minute${tdiff === 1? '' : 's'} ago`;
}
tdiff = Math.floor(tdiff/60);
if (tdiff < 24) {
return `${tdiff} hour${tdiff === 1? '' : 's'} ago`;
}
if (tdiff < 48) {
return `Yesterday`;
}
2022-10-05 03:41:59 +00:00
if (oDate.getFullYear() != now.getFullYear())
return toHumanReadableDate(oDate);
return toHumanReadableDate(oDate, {year: true});
2022-04-28 01:55:18 +00:00
}
function isValid(date: any) {
return (new Date(date)).toString() === 'Invalid Date';
}
2022-10-05 03:41:59 +00:00
const DateTool = {
toRelativeDate,
2022-04-28 01:55:18 +00:00
isValid
};
2022-04-28 01:55:18 +00:00
export default DateTool;