swimtracker-app/SwimTracker/utility/TimeUtils.js

67 lines
1.9 KiB
JavaScript

import {i18n} from './i18n';
const locale = i18n.locale;
const fullDateFormat = Intl.DateTimeFormat(locale, {
weekday: "short",
year: "2-digit",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
const timeFormatter = Intl.DateTimeFormat(locale, {
hour: "2-digit",
minute: "2-digit",
});
/*
// Doesn't work on android yet (so use full time for now instead of relative time)
const relativeTimeFormatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto"});
const DIVISIONS = [
{ amount: 60, name: "seconds" },
{ amount: 60, name: "minutes" },
{ amount: 24, name: "hours" },
{ amount: 7, name: "days" },
{ amount: 4.34524, name: "weeks" },
{ amount: 12, name: "months" },
{ amount: Number.POSITIVE_INFINITY, name: "years" },
];
function formatTimeAgo(date) {
let duration = (date - new Date()) / 1000
for (let i = 0; i < DIVISIONS.length; i++) {
const division = DIVISIONS[i]
if (Math.abs(duration) < division.amount) {
const suffix = (division.name === "days") ? ", " + timeFormatter.format(date) : "";
return relativeTimeFormatter.format(Math.round(duration), division.name) + suffix
}
duration /= division.amount
}
}
*/
function timeSince(timeStamp) {
const now = Math.floor((new Date()).getTime() / 1000);
const secondsPassed = now - timeStamp;
const daysPassed = secondsPassed / 60 / 60 / 24;
const timeStampDate = new Date(timeStamp * 1000);
//if (daysPassed < 2)
// return formatTimeAgo(timeStampDate);
//else
return fullDateFormat.format(timeStampDate);
}
const toTimeStr = seconds => {
let minuteStr = String(Math.floor(seconds / 60));
if (minuteStr.length < 2)
minuteStr = "0" + minuteStr;
let secondStr = String(Math.floor(seconds % 60));
if (secondStr.length < 2)
secondStr = "0" + secondStr;
return minuteStr + ":" + secondStr;
}
export { toTimeStr, timeSince };