Openstatus
www.openstatus.dev
1import { endOfDay, isSameDay, startOfDay } from "date-fns";
2
3export function formatMilliseconds(ms: number) {
4 if (ms > 1000) {
5 return `${Intl.NumberFormat("en-US", {
6 style: "unit",
7 unit: "second",
8 maximumFractionDigits: 2,
9 }).format(ms / 1000)}`;
10 }
11
12 return `${Intl.NumberFormat("en-US", {
13 style: "unit",
14 unit: "millisecond",
15 }).format(ms)}`;
16}
17
18export function formatPercentage(value: number) {
19 if (Number.isNaN(value)) return "100%";
20 return `${Intl.NumberFormat("en-US", {
21 style: "percent",
22 minimumFractionDigits: 2,
23 maximumFractionDigits: 2,
24 }).format(value)}`;
25}
26
27export function formatNumber(value: number) {
28 return `${Intl.NumberFormat("en-US").format(value)}`;
29}
30
31// TODO: think of supporting custom formats
32
33export function formatDate(date: Date) {
34 return date.toLocaleDateString("en-US", {
35 year: "numeric",
36 month: "long",
37 day: "numeric",
38 });
39}
40
41export function formatDateTime(date: Date) {
42 return date.toLocaleDateString("en-US", {
43 month: "long",
44 day: "numeric",
45 hour: "numeric",
46 minute: "numeric",
47 });
48}
49
50export function formatTime(date: Date) {
51 return date.toLocaleTimeString("en-US", {
52 hour: "numeric",
53 minute: "numeric",
54 });
55}
56
57export function formatDateRange(from?: Date, to?: Date) {
58 const sameDay = from && to && isSameDay(from, to);
59 const isFromStartDay = from && startOfDay(from).getTime() === from.getTime();
60 const isToEndDay = to && endOfDay(to).getTime() === to.getTime();
61
62 if (sameDay) {
63 if (from && to) {
64 return `${formatDateTime(from)} - ${formatTime(to)}`;
65 }
66 }
67
68 if (from && to) {
69 if (isFromStartDay && isToEndDay) {
70 return `${formatDate(from)} - ${formatDate(to)}`;
71 }
72 return `${formatDateTime(from)} - ${formatDateTime(to)}`;
73 }
74
75 if (to) {
76 return `Until ${formatDateTime(to)}`;
77 }
78
79 if (from) {
80 return `Since ${formatDateTime(from)}`;
81 }
82
83 return "All time";
84}
85
86export function formatDateForInput(date: Date): string {
87 const year = date.getFullYear();
88 const month = String(date.getMonth() + 1).padStart(2, "0");
89 const day = String(date.getDate()).padStart(2, "0");
90 const hours = String(date.getHours()).padStart(2, "0");
91 const minutes = String(date.getMinutes()).padStart(2, "0");
92
93 return `${year}-${month}-${day}T${hours}:${minutes}`;
94}