🔀 Merge pull request #1217 from altearius/FEATURE/temporal-plurality

🩹 Singular/plural forms for time counts.
This commit is contained in:
Alicia Sykes 2023-06-10 12:21:13 +01:00 committed by GitHub
commit d718905779
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 6 deletions

View File

@ -141,12 +141,27 @@ export const getTimeDifference = (startTime, endTime) => {
const msDifference = new Date(endTime).getTime() - new Date(startTime).getTime();
const diff = Math.abs(Math.round(msDifference / 1000));
const divide = (time, round) => Math.round(time / round);
if (diff < 60) return `${divide(diff, 1)} seconds`;
if (diff < 3600) return `${divide(diff, 60)} minutes`;
if (diff < 86400) return `${divide(diff, 3600)} hours`;
if (diff < 604800) return `${divide(diff, 86400)} days`;
if (diff < 31557600) return `${divide(diff, 604800)} weeks`;
if (diff >= 31557600) return `${divide(diff, 31557600)} years`;
const periods = [
{ noun: 'second', value: 1 },
{ noun: 'minute', value: 60 },
{ noun: 'hour', value: 3600 },
{ noun: 'day', value: 86400 },
{ noun: 'week', value: 604800 },
{ noun: 'fortnight', value: 1209600 },
{ noun: 'month', value: 2628000 },
{ noun: 'year', value: 31557600 },
];
for (let idx = 0; idx < periods.length; idx += 1) {
if (diff < (periods[idx + 1]?.value ?? Infinity)) {
const period = periods[idx];
const value = divide(diff, period.value);
const noun = value === 1 ? period.noun : `${period.noun}s`;
return `${value} ${noun}`;
}
}
return 'unknown';
};