timerender: Use date-fns for absolute_time.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2021-09-22 14:28:19 -07:00 committed by Anders Kaseorg
parent a0f8cf2d6f
commit af1e34b348
1 changed files with 15 additions and 49 deletions

View File

@ -306,56 +306,22 @@ export function stringify_time(time: number | Date): string {
// this is for rendering absolute time based off the preferences for twenty-four // this is for rendering absolute time based off the preferences for twenty-four
// hour time in the format of "%mmm %d, %h:%m %p". // hour time in the format of "%mmm %d, %h:%m %p".
export const absolute_time = (function () { export function absolute_time(timestamp: number, today = new Date()): string {
const MONTHS = [ const date = new Date(timestamp);
"Jan", const is_older_year = today.getFullYear() - date.getFullYear() > 0;
"Feb", const H_24 = user_settings.twenty_four_hour_time;
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
const fmt_time = function (date: Date, H_24: boolean): string { return format(
const payload = { date,
hours: date.getHours(), is_older_year
minutes: date.getMinutes(), ? H_24
is_pm: false, ? "MMM d, yyyy HH:mm"
}; : "MMM d, yyyy hh:mm a"
: H_24
if (payload.hours > 12 && !H_24) { ? "MMM d HH:mm"
payload.hours -= 12; : "MMM d hh:mm a",
payload.is_pm = true; );
} }
let str = ("0" + payload.hours).slice(-2) + ":" + ("0" + payload.minutes).slice(-2);
if (!H_24) {
str += payload.is_pm ? " PM" : " AM";
}
return str;
};
return function (timestamp: number, today = new Date()): string {
const date = new Date(timestamp);
const is_older_year = today.getFullYear() - date.getFullYear() > 0;
const H_24 = user_settings.twenty_four_hour_time;
let str = MONTHS[date.getMonth()] + " " + date.getDate();
// include year if message date is from a previous year
if (is_older_year) {
str += ", " + date.getFullYear();
}
str += " " + fmt_time(date, H_24);
return str;
};
})();
export function get_full_datetime(time: Date): string { export function get_full_datetime(time: Date): string {
const time_options: Intl.DateTimeFormatOptions = {timeStyle: "medium"}; const time_options: Intl.DateTimeFormatOptions = {timeStyle: "medium"};