1
1
import { prettyNumber } from '../utils.js' ;
2
2
3
3
const { lang} = document . documentElement ;
4
+
4
5
const dateFormatter = new Intl . DateTimeFormat ( lang , { year : 'numeric' , month : 'long' , day : 'numeric' } ) ;
6
+ const shortDateFormatter = new Intl . DateTimeFormat ( lang , { year : 'numeric' , month : 'short' , day : 'numeric' } ) ;
7
+ const dateTimeFormatter = new Intl . DateTimeFormat ( lang , { year : 'numeric' , month : 'short' , day : 'numeric' , hour : 'numeric' , minute : 'numeric' , second : 'numeric' } ) ;
5
8
6
9
export function initFormattingReplacements ( ) {
7
10
// replace english formatted numbers with locale-specific separators
@@ -13,9 +16,28 @@ export function initFormattingReplacements() {
13
16
}
14
17
}
15
18
16
- // for each <time></time> tag, if it has the data-format="date" attribute, format
17
- // the text according to the user's chosen locale
18
- for ( const timeElement of document . querySelectorAll ( 'time[data-format="date"]' ) ) {
19
- timeElement . textContent = dateFormatter . format ( new Date ( timeElement . dateTime ) ) ;
19
+ // for each <time></time> tag, if it has the data-format attribute, format
20
+ // the text according to the user's chosen locale and formatter.
21
+ formatAllTimeElements ( ) ;
22
+ }
23
+
24
+ function formatAllTimeElements ( ) {
25
+ const timeElements = document . querySelectorAll ( 'time[data-format]' ) ;
26
+ for ( const timeElement of timeElements ) {
27
+ const formatter = getFormatter ( timeElement . dataset . format ) ;
28
+ timeElement . textContent = formatter . format ( new Date ( timeElement . dateTime ) ) ;
29
+ }
30
+ }
31
+
32
+ function getFormatter ( format ) {
33
+ switch ( format ) {
34
+ case 'date' :
35
+ return dateFormatter ;
36
+ case 'short-date' :
37
+ return shortDateFormatter ;
38
+ case 'date-time' :
39
+ return dateTimeFormatter ;
40
+ default :
41
+ throw new Error ( 'Unknown format' ) ;
20
42
}
21
43
}
0 commit comments