Skip to content

Instantly share code, notes, and snippets.

@source-c
Created October 24, 2024 10:54
Show Gist options
  • Save source-c/645cf7e35978c197bf0f285c586f37e6 to your computer and use it in GitHub Desktop.
Save source-c/645cf7e35978c197bf0f285c586f37e6 to your computer and use it in GitHub Desktop.
Typescript generic time helpers
import {format as dateFmt} from 'date-fns'
export const getRelativeTime = (locale: string, d1: Date, d2: Date = new Date()): string => {
// in milliseconds
const units = {
year: 24 * 60 * 60 * 1000 * 365,
month: 24 * 60 * 60 * 1000 * 365 / 12,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
}
const rtf = new Intl.RelativeTimeFormat(locale, {numeric: 'auto'})
const elapsed: number = +d1 - +d2
// "Math.abs" accounts for both "past" & "future" scenarios
for (const u in units)
if (Math.abs(elapsed) > units[u] || u == 'second')
return rtf.format(Math.round(elapsed / units[u]), u as Intl.RelativeTimeFormatUnit)
return d1.toString()
}
export const formatDateTime = (date: number | string | Date) => {
return dateFmt(new Date(date), 'yyyy.MM.dd HH:mm:ss');
};
export const formatDateBackend = (date: number | string | Date) => {
return dateFmt(new Date(date), 'yyyy-MM-dd');
};
export const uuidV1ToTimestamp = (uuid_str: string) => {
try {
const uuid_arr = uuid_str.split('-'),
time_str = [
uuid_arr[2].substring(1),
uuid_arr[1],
uuid_arr[0]
].join('');
return Math.floor((parseInt(time_str, 16) - 122192928000000000) / 10000);
} catch (e) {
console.error(e);
return -1;
}
};
export const uuidToTime = (uuid: string) => {
const noTime = null;
if (uuid) {
return formatDateTime(uuidV1ToTimestamp(uuid)) || noTime;
} else return noTime;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment