forked from
quillmatiq.com/augment
Fork of Chiri for Astro for my blog
1import { themeConfig } from '@/config'
2import type { DateFormat } from '@/types'
3
4const MONTHS_EN = [
5 'Jan',
6 'Feb',
7 'Mar',
8 'Apr',
9 'May',
10 'Jun',
11 'Jul',
12 'Aug',
13 'Sep',
14 'Oct',
15 'Nov',
16 'Dec'
17]
18
19const VALID_SEPARATORS = ['.', '-', '/']
20
21/**
22 * @param date
23 * @param format
24 * @returns
25 */
26export function formatDate(date: Date, format?: string): string {
27 const formatStr = (format || themeConfig.date.dateFormat).trim()
28 const configSeparator = themeConfig.date.dateSeparator || '-'
29
30 const separator = VALID_SEPARATORS.includes(configSeparator.trim()) ? configSeparator.trim() : '.'
31
32 const year = date.getFullYear()
33 const month = date.getMonth() + 1
34 const day = date.getDate()
35 const monthName = MONTHS_EN[date.getMonth()]
36
37 const pad = (num: number) => String(num).padStart(2, '0')
38
39 switch (formatStr) {
40 case 'YYYY-MM-DD':
41 return `${year}${separator}${pad(month)}${separator}${pad(day)}`
42
43 case 'MM-DD-YYYY':
44 return `${pad(month)}${separator}${pad(day)}${separator}${year}`
45
46 case 'DD-MM-YYYY':
47 return `${pad(day)}${separator}${pad(month)}${separator}${year}`
48
49 case 'MONTH DAY YYYY':
50 return `<span class="month">${monthName}</span> ${day} ${year}`
51
52 case 'DAY MONTH YYYY':
53 return `${day} <span class="month">${monthName}</span> ${year}`
54
55 default:
56 return `${year}${separator}${pad(month)}${separator}${pad(day)}`
57 }
58}
59
60export const SUPPORTED_DATE_FORMATS: readonly DateFormat[] = [
61 'YYYY-MM-DD',
62 'MM-DD-YYYY',
63 'DD-MM-YYYY',
64 'MONTH DAY YYYY',
65 'DAY MONTH YYYY'
66] as const