-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateFormatter.ts
More file actions
82 lines (68 loc) · 1.79 KB
/
DateFormatter.ts
File metadata and controls
82 lines (68 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { DateTime } from 'luxon';
import Formatter from './Formatter';
/**
* @TODO: use moment or some other library
*/
const fix = (num, length = 2) => String(num).padStart(length, '0');
const replacers = {
yyyy(date) {
return date.getFullYear();
},
YYYY(date) {
return date.getFullYear();
},
MM(date) {
return fix(date.getMonth() + 1);
},
dd(date) {
return fix(date.getDate());
},
QQ(date) {
return `Q${Math.ceil((date.getMonth() + 1) / 3)}`;
},
DD(date) {
return fix(date.getDate());
},
HH(date) {
return fix(date.getHours());
},
mm(date) {
return fix(date.getMinutes());
},
ss(date) {
return fix(date.getSeconds());
},
ms(date) {
return fix(date.getMilliseconds(), 3);
},
};
const trunk = new RegExp(Object.keys(replacers).join('|'), 'g');
export class DateFormatter extends Formatter {
pattern: string;
constructor(pattern = 'YYYY-MM-DD HH:mm:ss') {
super();
this.pattern = pattern;
}
format(value, pattern) {
pattern = pattern || this.pattern;
if (pattern === `yyyy-MM-dd'T'HH:mm:ss.SSSxxx`) {
let dt =
value instanceof Date
? DateTime.fromJSDate(value)
: typeof value === 'string' && value?.includes('T')
? DateTime.fromISO(value)
: DateTime.fromJSDate(new Date(value));
return dt.toFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
}
if (value && !isNaN(value)) value = +value;
const date = new Date(value);
if (String(date) === 'Invalid Date') return value;
return pattern.replace(trunk, (cap) => (replacers[cap] ? replacers[cap](date) : ''));
}
parse(value, pattern) {
pattern = pattern || this.pattern;
return new Date(value);
}
}
export const dateFormatter = new DateFormatter();
export default DateFormatter;