PluginProbe
The Innovative Form Builder – IvyForms / 0.2
The Innovative Form Builder – IvyForms v0.2
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.2, at frontend/src/utils/utilDateFormatter.ts

60 lines 1.7 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
4 function convertWPFormat(wpFormat: string, target: 'dateFns' | 'dayjs' = 'dateFns'): string {
5 const map: Record<string, { dayjs?: string; dateFns?: string; all?: string }> = {
6 Y: { dayjs: 'YYYY', dateFns: 'yyyy' },
7 y: { dayjs: 'YY', dateFns: 'yy' },
8 F: { all: 'MMMM' },
9 M: { dayjs: 'MMM', dateFns: 'MMM' },
10 m: { all: 'MM' },
11 n: { all: 'M' },
12 d: { dayjs: 'DD', dateFns: 'dd' },
13 j: { dayjs: 'D', dateFns: 'd' },
14 D: { dayjs: 'ddd', dateFns: 'eee' },
15 l: { dayjs: 'dddd', dateFns: 'eeee' },
16 }
17
18 return wpFormat.replace(/\b[a-zA-Z]\b/g, (token) => {
19 const formats = map[token]
20 return formats?.[target] || formats?.all || token
21 })
22 }
23
24 function formatWPDate(date: string | number | Date | null | undefined | boolean): string {
25 // Handle null, undefined, or boolean values
26 if (!date || typeof date === 'boolean') return ''
27
28 let jsDate: Date
29
30 if (typeof date === 'string') {
31 if (date.trim() === '') return ''
32 jsDate = new Date(date)
33 if (isNaN(jsDate.getTime())) return ''
34 } else if (typeof date === 'number') {
35 if (date === 0) return ''
36 jsDate = new Date(date)
37 if (isNaN(jsDate.getTime())) return ''
38 } else if (date instanceof Date) {
39 jsDate = date
40 if (isNaN(jsDate.getTime())) return ''
41 } else {
42 return ''
43 }
44
45 const wpFormat = window.wpIvyDateFormat?.dateFormat || 'dd MMM yyyy'
46 const locale = window.wpIvyDateFormat?.locale === 'sr_RS' ? sr : enGB
47 const dateFnsFormat = convertWPFormat(wpFormat, 'dateFns')
48
49 try {
50 return format(jsDate, dateFnsFormat, { locale })
51 } catch {
52 return ''
53 }
54 }
55
56 export default {
57 formatWPDate,
58 convertWPFormat,
59 }
60