OSDN Git Service

Regular updates
[twpd/master.git] / wip / intl-datetime.md
1 ---
2 title: Intl.DateTimeFormat
3 category: Hidden
4 layout: 2017/sheet
5 tags: [WIP]
6 intro: |
7   `Intl.DateTimeFormat` is used to format date strings in JavaScript.
8 ---
9
10 ### Parsing
11
12 #### As local time
13
14 ```js
15 const date = new Date(2012, 11, 20, 3, 0, 0)
16 ```
17
18 #### As UTC time
19
20 ```js
21 const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0))
22 ```
23
24 #### From ISO strings
25
26 ```js
27 const date = new Date('2018-04-20T12:00:00Z')
28 ```
29
30 Note that JavaScript doesn't "store" timezones in a date object. All these date objects, when expressed via `.toString()` or similar, will show the local timezone of the browser, regardless if you parsed UTC dates.
31
32 ### Formatting dates
33
34 #### Default formatting
35
36 ```js
37 console.log(new Intl.DateTimeFormat().format(date))
38 // → '12/19/2012' (assuming America/Los_Angeles)
39 ```
40
41 #### Custom locale
42
43 ```js
44 console.log(new Intl.DateTimeFormat('en-GB').format(date))
45 // → '19/12/2012' (date-first)
46 ```
47
48 #### Custom timezone
49
50 ```js
51 console.log(new Intl.DateTimeFormat('en-AU', {
52   timeZone: 'Australia/Sydney'
53 }).format(date))
54 // → '19/12/2012'
55 ```
56
57 ### Custom formats
58
59 #### Time
60
61 ```js
62 console.log(new Intl.DateTimeFormat('default', {
63   hour: 'numeric',
64   minute: 'numeric',
65   second: 'numeric'
66 }).format(date))
67 // → '2:00:00 pm'
68 ```
69
70 #### Date
71
72 ```js
73 console.log(new Intl.DateTimeFormat('en-US', {
74   year: 'numeric',
75   month: 'numeric',
76   day: 'numeric'
77 }).format(date))
78 // → '12/19/2012'
79 ```
80
81 To specify options without a locale, use `'default'` as a locale.
82
83 ### All options
84
85 ```js
86 {
87   weekday: 'narrow' | 'short' | 'long',
88   era: 'narrow' | 'short' | 'long',
89   year: 'numeric' | '2-digit',
90   month: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long',
91   day: 'numeric' | '2-digit',
92   hour: 'numeric' | '2-digit',
93   minute: 'numeric' | '2-digit',
94   second: 'numeric' | '2-digit',
95   timeZoneName: 'short' | 'long',
96
97   // Time zone to express it in
98   timeZone: 'Asia/Shanghai',
99   // Force 12-hour or 24-hour
100   hour12: true | false,
101
102   // Rarely-used options
103   hourCycle: 'h11' | 'h12' | 'h23' | 'h24',
104   formatMatcher: 'basic' | 'best fit'
105 }
106 ```
107
108
109 ## References
110
111 - <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat>