Massive/time.ts

62 lines
1.5 KiB
TypeScript
Raw Normal View History

export const DAYS = [
2022-07-09 04:38:57 +00:00
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
2022-10-31 04:22:08 +00:00
]
2022-07-09 04:38:57 +00:00
2022-07-11 01:00:17 +00:00
export function formatMonth(iso: string) {
2022-10-31 04:22:08 +00:00
const date = new Date(iso)
const dd = date.getDate().toString()
const mm = (date.getMonth() + 1).toString()
return `${dd}/${mm}`
2022-07-11 01:00:17 +00:00
}
function twelveHour(twentyFourHour: string) {
2022-10-31 04:22:08 +00:00
const [hourString, minute] = twentyFourHour.split(':')
const hour = +hourString % 24
return (hour % 12 || 12) + ':' + minute + (hour < 12 ? ' AM' : ' PM')
}
function dayOfWeek(iso: string) {
2022-10-31 04:22:08 +00:00
const date = new Date(iso)
const day = date.getDay()
const target = DAYS[day]
return target.slice(0, 3)
}
/**
* @param iso ISO formatted date, e.g. 1996-12-24T14:03:04
* @param kind Intended format for the date, e.g. '%Y-%m-%d %H:%M'
*/
export function format(iso: string, kind: string) {
2022-10-31 04:22:08 +00:00
const split = iso.split('T')
const [year, month, day] = split[0].split('-')
const time = twelveHour(split[1])
switch (kind) {
case '%Y-%m-%d %H:%M':
2022-10-31 04:22:08 +00:00
return iso.replace('T', ' ').replace(/:\d{2}/, '')
case '%Y-%m-%d':
2022-10-31 04:22:08 +00:00
return split[0]
case '%H:%M':
2022-10-31 04:22:08 +00:00
return split[1].replace(/:\d{2}/, '')
case '%d/%m/%y %h:%M %p':
2022-10-31 04:22:08 +00:00
return `${day}/${month}/${year} ${time}`
case '%d/%m %h:%M %p':
2022-10-31 04:22:08 +00:00
return `${day}/${month} ${time}`
case '%d/%m/%y':
2022-10-31 04:22:08 +00:00
return `${day}/${month}/${year}`
case '%d/%m':
2022-10-31 04:22:08 +00:00
return `${day}/${month}`
case '%h:%M %p':
2022-10-31 04:22:08 +00:00
return time
case '%A %h:%M %p':
2022-10-31 04:22:08 +00:00
return dayOfWeek(iso) + ' ' + time
default:
2022-10-31 04:22:08 +00:00
return iso
}
}