2020-01-14 12:20:01 +08:00
|
|
|
/*
|
2024-09-09 21:57:16 +08:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2021-06-07 17:57:46 +08:00
|
|
|
Copyright 2020, 2021 The Matrix.org Foundation C.I.C.
|
2020-01-14 12:20:01 +08:00
|
|
|
|
2024-09-09 21:57:16 +08:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
|
|
|
Please see LICENSE files in the repository root for full details.
|
2020-01-14 12:20:01 +08:00
|
|
|
*/
|
|
|
|
|
2021-06-07 17:57:46 +08:00
|
|
|
import { _t } from "../languageHandler";
|
|
|
|
|
|
|
|
// These are the constants we use for when to break the text
|
|
|
|
const MILLISECONDS_RECENT = 15000;
|
|
|
|
const MILLISECONDS_1_MIN = 75000;
|
|
|
|
const MINUTES_UNDER_1_HOUR = 45;
|
|
|
|
const MINUTES_1_HOUR = 75;
|
|
|
|
const HOURS_UNDER_1_DAY = 23;
|
|
|
|
const HOURS_1_DAY = 26;
|
2020-01-14 12:20:01 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts a timestamp into human-readable, translated, text.
|
|
|
|
* @param {number} timeMillis The time in millis to compare against.
|
|
|
|
* @returns {string} The humanized time.
|
|
|
|
*/
|
2021-06-07 17:57:46 +08:00
|
|
|
export function humanizeTime(timeMillis: number): string {
|
2022-04-20 19:57:50 +08:00
|
|
|
const now = Date.now();
|
2020-01-14 12:20:01 +08:00
|
|
|
let msAgo = now - timeMillis;
|
|
|
|
const minutes = Math.abs(Math.ceil(msAgo / 60000));
|
|
|
|
const hours = Math.ceil(minutes / 60);
|
|
|
|
const days = Math.ceil(hours / 24);
|
|
|
|
|
|
|
|
if (msAgo >= 0) {
|
|
|
|
// Past
|
2023-09-04 17:20:34 +08:00
|
|
|
if (msAgo <= MILLISECONDS_RECENT) return _t("time|few_seconds_ago");
|
|
|
|
if (msAgo <= MILLISECONDS_1_MIN) return _t("time|about_minute_ago");
|
|
|
|
if (minutes <= MINUTES_UNDER_1_HOUR) return _t("time|n_minutes_ago", { num: minutes });
|
|
|
|
if (minutes <= MINUTES_1_HOUR) return _t("time|about_hour_ago");
|
|
|
|
if (hours <= HOURS_UNDER_1_DAY) return _t("time|n_hours_ago", { num: hours });
|
|
|
|
if (hours <= HOURS_1_DAY) return _t("time|about_day_ago");
|
|
|
|
return _t("time|n_days_ago", { num: days });
|
2020-01-14 12:20:01 +08:00
|
|
|
} else {
|
|
|
|
// Future
|
|
|
|
msAgo = Math.abs(msAgo);
|
2023-09-04 17:20:34 +08:00
|
|
|
if (msAgo <= MILLISECONDS_RECENT) return _t("time|in_few_seconds");
|
|
|
|
if (msAgo <= MILLISECONDS_1_MIN) return _t("time|in_about_minute");
|
|
|
|
if (minutes <= MINUTES_UNDER_1_HOUR) return _t("time|in_n_minutes", { num: minutes });
|
|
|
|
if (minutes <= MINUTES_1_HOUR) return _t("time|in_about_hour");
|
|
|
|
if (hours <= HOURS_UNDER_1_DAY) return _t("time|in_n_hours", { num: hours });
|
|
|
|
if (hours <= HOURS_1_DAY) return _t("time|in_about_day");
|
|
|
|
return _t("time|in_n_days", { num: days });
|
2020-01-14 12:20:01 +08:00
|
|
|
}
|
|
|
|
}
|