1import {t} from "i18next";
2import {SPEED_UNIT_MBPS, SPEED_UNIT_MBYTES, TIME_FORMAT_12H, TIME_FORMAT_24H} from "@/common/contexts/Preferences";
3
4const toDate = (value) => {
5 if (value instanceof Date) return value;
6 return new Date(value);
7};
8
9export const formatTime = (value, preferences) => {
10 const date = toDate(value);
11 if (isNaN(date.getTime())) return "";
12
13 const use12h = preferences?.timeFormat === TIME_FORMAT_12H;
14 return date.toLocaleTimeString(undefined, {
15 hour: "2-digit",
16 minute: "2-digit",
17 hour12: use12h
18 });
19};
20
21export const formatDateTime = (value, preferences, dateOptions = {}) => {
22 const date = toDate(value);
23 if (isNaN(date.getTime())) return "";
24
25 const use12h = preferences?.timeFormat === TIME_FORMAT_12H;
26 const datePart = date.toLocaleDateString(undefined, dateOptions);
27 const timePart = date.toLocaleTimeString(undefined, {
28 hour: "2-digit",
29 minute: "2-digit",
30 hour12: use12h
31 });
32 return `${datePart} ${timePart}`;
33};
34
35export const formatShortTime = (date, preferences) => {
36 const use12h = preferences?.timeFormat === TIME_FORMAT_12H;
37 if (use12h) {
38 let hours = date.getHours();
39 const minutes = String(date.getMinutes()).padStart(2, "0");
40 const suffix = hours >= 12 ? "PM" : "AM";
41 hours = hours % 12;
42 if (hours === 0) hours = 12;
43 return `${hours}:${minutes} ${suffix}`;
44 }
45 const hours = String(date.getHours()).padStart(2, "0");
46 const minutes = String(date.getMinutes()).padStart(2, "0");
47 return `${hours}:${minutes}`;
48};
49
50export const getSpeedUnit = (preferences) => {
51 if (preferences?.speedUnit === SPEED_UNIT_MBYTES) {
52 return t("latest.byte_speed_unit", {defaultValue: "MB/s"});
53 }
54 return t("latest.speed_unit");
55};
56
57export const convertSpeed = (mbps, preferences) => {
58 if (mbps === null || mbps === undefined) return mbps;
59 if (typeof mbps !== "number" || isNaN(mbps)) return mbps;
60 if (mbps < 0) return mbps;
61
62 if (preferences?.speedUnit === SPEED_UNIT_MBYTES) {
63 return Math.round((mbps / 8) * 100) / 100;
64 }
65 return mbps;
66};
67
68export {SPEED_UNIT_MBPS, SPEED_UNIT_MBYTES, TIME_FORMAT_12H, TIME_FORMAT_24H};
69