2022-08-26 16:08:58 +02:00
|
|
|
import type { Locale } from "date-fns";
|
|
|
|
import { format } from "date-fns";
|
|
|
|
|
2019-10-11 18:41:29 +02:00
|
|
|
function localeMonthNames(): string[] {
|
|
|
|
const monthNames: string[] = [];
|
|
|
|
for (let i = 0; i < 12; i += 1) {
|
|
|
|
const d = new Date(2019, i, 1);
|
2020-02-18 08:57:00 +01:00
|
|
|
const month = d.toLocaleString("default", { month: "long" });
|
2019-10-11 18:41:29 +02:00
|
|
|
monthNames.push(month);
|
|
|
|
}
|
|
|
|
return monthNames;
|
|
|
|
}
|
|
|
|
|
|
|
|
function localeShortWeekDayNames(): string[] {
|
|
|
|
const weekDayNames: string[] = [];
|
|
|
|
for (let i = 13; i < 20; i += 1) {
|
|
|
|
const d = new Date(2019, 9, i);
|
2020-02-18 08:57:00 +01:00
|
|
|
const weekDay = d.toLocaleString("default", { weekday: "short" });
|
2019-10-11 18:41:29 +02:00
|
|
|
weekDayNames.push(weekDay);
|
|
|
|
}
|
|
|
|
return weekDayNames;
|
|
|
|
}
|
|
|
|
|
2020-11-23 16:58:50 +01:00
|
|
|
// https://stackoverflow.com/a/18650828/10204399
|
2022-08-29 16:52:18 +02:00
|
|
|
function formatBytes(
|
|
|
|
bytes: number,
|
|
|
|
decimals = 2,
|
|
|
|
locale: string | undefined = undefined
|
|
|
|
): string {
|
|
|
|
const formatNumber = (value = 0, unit = "byte") =>
|
|
|
|
new Intl.NumberFormat(locale, {
|
|
|
|
style: "unit",
|
|
|
|
unit,
|
|
|
|
unitDisplay: "long",
|
|
|
|
}).format(value);
|
|
|
|
|
|
|
|
if (bytes === 0) return formatNumber(0);
|
|
|
|
if (bytes < 0 || bytes > Number.MAX_SAFE_INTEGER) {
|
|
|
|
throw new RangeError(
|
|
|
|
"Number mustn't be negative and be inferior to Number.MAX_SAFE_INTEGER"
|
|
|
|
);
|
|
|
|
}
|
2020-11-23 16:58:50 +01:00
|
|
|
|
|
|
|
const k = 1024;
|
|
|
|
const dm = decimals < 0 ? 0 : decimals;
|
2022-08-29 16:52:18 +02:00
|
|
|
const sizes = [
|
|
|
|
"byte",
|
|
|
|
"kilobyte",
|
|
|
|
"megabyte",
|
|
|
|
"gigabyte",
|
|
|
|
"terabyte",
|
|
|
|
"petabyte",
|
|
|
|
];
|
2020-11-23 16:58:50 +01:00
|
|
|
|
|
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
|
|
|
2022-08-29 16:52:18 +02:00
|
|
|
return formatNumber(parseFloat((bytes / k ** i).toFixed(dm)), sizes[i]);
|
2020-11-23 16:58:50 +01:00
|
|
|
}
|
|
|
|
|
2022-08-26 16:08:58 +02:00
|
|
|
function roundToNearestMinute(date = new Date()) {
|
|
|
|
const minutes = 1;
|
|
|
|
const ms = 1000 * 60 * minutes;
|
|
|
|
|
|
|
|
// 👇️ replace Math.round with Math.ceil to always round UP
|
|
|
|
return new Date(Math.round(date.getTime() / ms) * ms);
|
|
|
|
}
|
|
|
|
|
|
|
|
function formatDateTimeForEvent(dateTime: Date, locale: Locale): string {
|
|
|
|
return format(dateTime, "PPp", { locale });
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
localeMonthNames,
|
|
|
|
localeShortWeekDayNames,
|
|
|
|
formatBytes,
|
|
|
|
roundToNearestMinute,
|
|
|
|
formatDateTimeForEvent,
|
|
|
|
};
|