PluginProbe
The Innovative Form Builder – IvyForms / 0.8
The Innovative Form Builder – IvyForms v0.8
1.5.1 1.5 1.4.1 1.4 trunk 0.1.2 0.2 0.2.1 0.3 0.3.1 0.4 0.5 0.6 0.6.1 0.6.1-backup 0.6.1.1 0.7 0.8 0.8.1 0.8.2 0.9 0.9.1 1.0 1.1 1.1.1 All 27 releases
ivyforms / frontend / src / utils / utilDateFormatter.ts

utilDateFormatter.ts in The Innovative Form Builder – IvyForms 0.8, at frontend/src/utils/utilDateFormatter.ts

82 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { format } from 'date-fns'
2 import { enGB, sr } from 'date-fns/locale'
3 import dayjs from 'dayjs'
4
5 function convertWPFormat(wpFormat: string, target: 'dateFns' | 'dayjs' = 'dateFns'): string {
6 const map: Record<string, { dayjs?: string; dateFns?: string; all?: string }> = {
7 Y: { dayjs: 'YYYY', dateFns: 'yyyy' },
8 y: { dayjs: 'YY', dateFns: 'yy' },
9 F: { all: 'MMMM' },
10 M: { dayjs: 'MMM', dateFns: 'MMM' },
11 m: { all: 'MM' },
12 n: { all: 'M' },
13 d: { dayjs: 'DD', dateFns: 'dd' },
14 j: { dayjs: 'D', dateFns: 'd' },
15 D: { dayjs: 'ddd', dateFns: 'eee' },
16 l: { dayjs: 'dddd', dateFns: 'eeee' },
17 }
18
19 return wpFormat.replace(/\b[a-zA-Z]\b/g, (token) => {
20 const formats = map[token]
21 return formats?.[target] || formats?.all || token
22 })
23 }
24
25 function formatWPDate(date: string | number | Date | null | undefined | boolean): string {
26 // Handle null, undefined, or boolean values
27 if (!date || typeof date === 'boolean') return ''
28
29 let jsDate: Date
30
31 if (typeof date === 'string') {
32 if (date.trim() === '') return ''
33 jsDate = new Date(date)
34 if (isNaN(jsDate.getTime())) return ''
35 } else if (typeof date === 'number') {
36 if (date === 0) return ''
37 jsDate = new Date(date)
38 if (isNaN(jsDate.getTime())) return ''
39 } else if (date instanceof Date) {
40 jsDate = date
41 if (isNaN(jsDate.getTime())) return ''
42 } else {
43 return ''
44 }
45
46 const wpFormat = window.wpIvyDateFormat?.dateFormat || 'dd MMM yyyy'
47 const locale = window.wpIvyDateFormat?.locale === 'sr_RS' ? sr : enGB
48 const dateFnsFormat = convertWPFormat(wpFormat, 'dateFns')
49
50 try {
51 return format(jsDate, dateFnsFormat, { locale })
52 } catch {
53 return ''
54 }
55 }
56
57 function formatDateRangeForApi(dateValue: unknown): string[] {
58 if (Array.isArray(dateValue)) {
59 return dateValue
60 .map((d) =>
61 typeof d === 'string' || typeof d === 'number' || d instanceof Date || dayjs.isDayjs(d)
62 ? dayjs(d).format('YYYY-MM-DD')
63 : null,
64 )
65 .filter(Boolean) as string[]
66 } else if (
67 typeof dateValue === 'string' ||
68 typeof dateValue === 'number' ||
69 dateValue instanceof Date ||
70 dayjs.isDayjs(dateValue)
71 ) {
72 return [dayjs(dateValue).format('YYYY-MM-DD')]
73 }
74 return []
75 }
76
77 export default {
78 formatWPDate,
79 convertWPFormat,
80 formatDateRangeForApi,
81 }
82