This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
scoresaber-reloadedv3/src/common/time-utils.ts

78 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-09-11 20:10:27 +01:00
/**
* This function returns the time ago of the input date
*
* @param input Date | number
* @returns the format of the time ago
*/
export function timeAgo(input: Date | number) {
const date = input instanceof Date ? input : new Date(input);
const formatter = new Intl.RelativeTimeFormat("en");
const ranges: { [key: string]: number } = {
2024-09-11 20:15:05 +01:00
year: 3600 * 24 * 365,
month: 3600 * 24 * 30,
week: 3600 * 24 * 7,
day: 3600 * 24,
hour: 3600,
minute: 60,
second: 1,
2024-09-11 20:10:27 +01:00
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
2024-09-11 20:16:33 +01:00
for (const key in ranges) {
2024-09-11 20:10:27 +01:00
if (ranges[key] < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / ranges[key];
2024-09-13 13:45:04 +01:00
return formatter.format(
Math.round(delta),
key as Intl.RelativeTimeFormatUnit,
);
2024-09-11 20:10:27 +01:00
}
}
}
2024-09-28 05:57:35 +01:00
/**
* Gets the midnight aligned date
*
* @param date the date
*/
export function getMidnightAlignedDate(date: Date) {
2024-09-28 06:16:09 +01:00
const midnightDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
);
midnightDate.setUTCHours(0, 0, 0, 0);
return midnightDate;
2024-09-28 05:57:35 +01:00
}
/**
* Gets the date X days ago
*
* @param days the number of days to go back
* @returns {Date} A Date object representing the date X days ago
*/
export function getDaysAgoDate(days: number): Date {
const date = new Date();
date.setDate(date.getDate() - days);
return date;
}
/**
* Gets the amount of days ago a date was
*
* @param date the date
* @returns the amount of days
*/
export function getDaysAgo(date: Date): number {
const now = new Date();
const diffTime = Math.abs(now.getTime() - date.getTime());
return Math.ceil(diffTime / (1000 * 60 * 60 * 24)) - 1;
}
/**
* Parses a date from a string
*
* @param date the date
*/
export function parseDate(date: string): Date {
return new Date(date);
}