• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Date and Time Formatting
2
3## Use Cases
4
5The date and time formats vary according to countries and cultures. The difference lies in such aspects as the sequence of year, month, and day in a date and the separator of hour, minute, and second in the time. If your application needs to display the date and time, ensure that the information is displayed in line with local user habits for easy understanding.
6
7Time and date formatting includes date and time formatting, relative time formatting, and time segment formatting. Date and time formatting means to convert the date and time into a string in the specified format. Relative time formatting means to convert the time difference between a time point and another time point to the specified format, for example, 30 seconds ago or 1 day later. Time segment formatting means to convert a time segment to the specified format, for example, Wednesday or 8:00-11:30.
8
9## Constraints
10
111. **dateStyle** and **timeStyle** must be set simultaneously. If only **timeStyle** is set, only the time is displayed. If only **dateStyle** is set, only the date is displayed.
12
132. If **dateStyle** or **timeStyle** is present, you are not allowed to specify the year, month, day, hour, minute, second, and workday formats. If **dateStyle** and **timeStyle** are not present, you can set the year, month, day, hour, minute, second, and workday formats independently.
14
15## How to Develop
16
17### Date and Time Formatting
18
19Date and time formatting is implemented by the [format](../reference/apis-localization-kit/js-apis-intl.md#format) API of [DateTimeFormat](../reference/apis-localization-kit/js-apis-intl.md#datetimeformat). The development procedure is as follows:
20
211. Import the **intl** module.
22   ```ts
23   import { intl } from '@kit.LocalizationKit';
24   ```
25
262. Create a **DateTimeFormat** object.
27   Pass a single locale ID or a list of locale IDs. If a list of locale IDs is passed, the first valid locale is used. If no locale is passed, the current system locale ID is used.
28   You can use **DateTimeOptions** to set different date and time formats. For details, see Table 1 to Table 10.
29
30   ```ts
31   let dateFormat: intl.DateTimeFormat = new intl.DateTimeFormat(locale: string | Array<string>, options?: DateTimeOptions);
32   let dateFormat: intl.DateTimeFormat = new intl.DateTimeFormat(); // Do not pass the locale parameter.
33   ```
34
353. Format the date and time.
36   ```ts
37   // Format the date and time.
38   let formattedDate: string = dateFormat.format(date: Date);
39
40   // Format the time segment.
41   let formattedDateRange: string = dateFormat.formatRange(startDate: Date, endDate: Date);
42   ```
43
444. Obtain **DateTimeOptions** and view the configuration of formatting options.
45   ```ts
46   let options: intl.DateTimeOptions = dateFormat.resolvedOptions();
47   ```
48
49**Date and Time Formatting Options**
50
51The following uses 13:04:00 and 00:25:00 on September 17, 2021 and locale IDs **zh-CN** and **en** as examples to illustrate the values and display results of [DateTimeOptions](../reference/apis-localization-kit/js-apis-intl.md#datetimeoptions).
52
53**Table 1** Date display format (dateStyle)
54
55| Value  | Description                                   | 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
56| ------ | --------------------------------------- | ------------------------------------------  | ---------------------------------------- |
57| full   | Complete date display, including the year, month, day, and week.| 2021年9月17日星期五                         | Friday, September 17, 2021               |
58| long   | Long date display, including the year, month, and day.    | 2021年9月17日                               | September 17, 2021                       |
59| short  | Short date display, including the year, month, and day.    | 2021/9/17                                   | 9/17/21                                  |
60| medium | Medium date display, including the year, month, and day.  | 2021年9月17日                               | Sep 17, 2021                             |
61
62**Table 2** Time display format (timeStyle)
63
64| Value  | Description| 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
65| ------ | ------------- | -------- | -------- |
66| full   | Complete time display, including the time zone and time accurate to seconds.| 中国标准时间 13:04:00 | 13:04:00 China Standard Time |
67| long   | Long time display, including the time zone expressed in the format of GMT + time zone offset and time accurate to seconds.| GMT+8 13:04:00 | 13:04:00 GMT+8 |
68| short  | Short time display, including hour and minute.| 13:04 | 13:04 |
69| medium | Medium time display, including hour, minute, and second.| 13:04:00 | 13:04:00 |
70
71**Table 3** Year display format (year)
72
73| Value| Description| 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
74| -------- | --------- | -------- | -------- |
75| numeric | Complete year| 2021年| 2021 |
76| 2-digit | 2-digit year display| 21年| 21 |
77
78**Table 4** Weekday display format (weekday)
79
80| Value| Description| 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
81| -------- | ------- | -------- | -------- |
82| long | Long weekday display| 星期五| Friday |
83| short | Short weekday display.| 周五| Fri |
84| narrow | Narrow weekday display.| 五| F |
85
86**Table 5** Hour cycle format (hourCycle)
87
88| Value| Description           | 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 00:25:00 for Locale ID zh-CN|
89| --- | --------------- | -------------------------------------------- | ------------------------------------------- |
90| h11 | Use of 0-11 to indicate the hour| 下午1:04                                    |  上午0:25                                   |
91| h12 | Use of 1-12 to indicate the hour| 下午1:04                                    |  上午12:25                                  |
92| h23 | Use of 0-23 to indicate the hour| 13:04                                        | 00:25                                       |
93| h24 | Use of 1-24 to indicate the hour| 13:04                                        | 24:25                                       |
94
95> **NOTE**
96>
97> The preceding table shows the display effect for different values of **hourCycle** when **dateStyle** or **timeStyle** is not set.
98
99
100**Table 6** Hour cycle format (hourCycle)
101
102| Value| Description           | 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 00:25:00 for Locale ID zh-CN|
103| --- | --------------- | -------------------------------------------- | ------------------------------------------- |
104| h11 | Use of 1-24 to indicate the hour| 下午13:04                                   |  上午24:25                                  |
105| h12 | Use of 1-12 to indicate the hour| 下午1:04                                    |  上午12:25                                  |
106| h23 | Use of 0-11 to indicate the hour| 1:04                                         |  0:25                                       |
107| h24 | Use of 0-23 to indicate the hour| 13:04                                        |  0:25                                       |
108
109> **NOTE**
110>
111> The preceding table shows the display effect for different values of **hourCycle** when **dateStyle** or **timeStyle** is set.
112
113**Table 7** Month format (month)
114
115| Value| Description| 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
116| -------- | --------- | -------- | -------- |
117| numeric | Display of the month as a number| 9月| 9 |
118| 2-digit | Display of the month in two digits| 09月| 09 |
119| long | Long month display| 九月| September |
120| short | Short month display| 9| Sep |
121| narrow | Narrow month display| 9 | S |
122
123**Table 8** Localized representation of time zone names (timeZoneName)
124
125| Value | Description               | 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
126| ----- | ------------------ | -------------------------------------------- | ---------------------------------------- |
127| long  | Long time zone name| 中国标准时间                                 | China Standard Time                      |
128| short | Short time zone name| GMT+8                                        | GMT+8                                    |
129
130**Table 9** Era display format (era)
131
132| Value| Description| 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
133| -------- | ------ | -------- | -------- |
134| long | Long epoch display| 公元| Anno Domini |
135| short | Short epoch display| 公元| AD |
136| narrow | Narrow epoch display| 公元| A |
137
138**Table 10** Time period format (dayPeriod)
139
140| Value| Description| 2021-09-17 13:04:00 for Locale ID zh-CN| 2021-09-17 13:04:00 for Locale ID en|
141| -------- | ------ | -------- | -------- |
142| long | Long time period display| 下午| in the afternoon |
143| short | Short time period display| 下午| in the afternoon |
144| narrow | Narrow time period display| 下午| in the afternoon |
145
146**Development Example**
147```ts
148// Import the intl module.
149import { intl } from '@kit.LocalizationKit';
150
151let date: Date = new Date(2021, 8, 17, 13, 4, 0); // The date and time is 2021.09.17 13:04:00.
152let startDate: Date = new Date(2021, 8, 17, 13, 4, 0);
153let endDate: Date = new Date(2021, 8, 18, 13, 4, 0);
154
155// Display complete time information.
156let fullFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'full' });
157let formattedDate: string = fullFormat.format(date); // formattedDate = 'Friday, September 17, 2021 China Standard Time 13:04:00'
158
159// Display short time information in limited space.
160let shortFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', { dateStyle: 'short', timeStyle: 'short' });
161formattedDate = shortFormat.format(date); // formattedDate = '2021/9/17 13:04'
162
163// Customize the display effect of year, month, day, hour, minute, and second.
164let customFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN',
165  {
166    year: 'numeric',
167    month: '2-digit',
168    day: '2-digit',
169    hour: '2-digit',
170    minute: '2-digit',
171    second: '2-digit'
172  });
173formattedDate = customFormat.format(date); // formattedDate = '2021/09/17 13:04:00'
174
175// Display only part of the time.
176let partialFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN',
177  {
178    month: 'long',
179    day: 'numeric',
180    weekday: 'long'
181  });
182formattedDate = partialFormat.format(date); // formattedDate = 'Friday, September 17'
183
184// Customize the date and time format.
185let hourCycleFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN',
186  {
187    dateStyle: 'short',
188    timeStyle: 'short',
189    hourCycle: 'h11'
190  });
191formattedDate = hourCycleFormat.format(date); // formattedDate = '2021/9/17 1:04 PM'
192
193// Customize the date and time format for users accustomed to other numeral systems.
194let numberingSystemFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN',
195  {
196    dateStyle: 'short',
197    timeStyle: 'short',
198    numberingSystem: 'arab'
199  });
200formattedDate = numberingSystemFormat.format(date); // formattedDate = '٢٠٢١/٩/١٧ ١٣:٠٤'
201
202// Format a time segment.
203let dateRangeFormat: intl.DateTimeFormat = new intl.DateTimeFormat('en-GB');
204let formattedDateRange: string =
205  dateRangeFormat.formatRange(startDate, endDate); // formattedDateRange = '17/09/2021 - 18/09/2021'
206
207// Obtain formatting options.
208let dateFormat: intl.DateTimeFormat = new intl.DateTimeFormat('en-GB', { dateStyle: 'full' });
209let options: intl.DateTimeOptions = dateFormat.resolvedOptions();
210let dateStyle: string | undefined = options.dateStyle; // dateStyle = 'full'
211```
212
213### Relative Time Formatting
214
215Relative time formatting is implemented by the [format](../reference/apis-localization-kit/js-apis-intl.md#format8) API of [RelativeTimeFormat](../reference/apis-localization-kit/js-apis-intl.md#relativetimeformat8). The development procedure is as follows:
216
2171. Import the **intl** module.
218   ```ts
219   import { intl } from '@kit.LocalizationKit';
220   ```
221
2222. Create a **RelativeTimeFormat** object.
223   You can use **RelativeTimeFormatInputOptions** to set different output message formats and message lengths. For details, see Table 7 and Table 8.
224   ```ts
225   let relativeTimeFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat(locale: string | Array<string>, options?: RelativeTimeFormatInputOptions);
226   ```
227
2283. Format the relative time. **value** indicates the formatted value, and **unit** indicates the formatted unit.
229   ```ts
230   let formattedRelativeTime: string = relativeTimeFormat.format(value: number, unit: string);
231   ```
232
2334. Format the custom relative time.
234   ```ts
235   let parts: Array<object> = relativeTimeFormat.formatToParts(value: number, unit: string);
236   ```
237
2385. Obtain **RelativeTimeFormatInputOptions** and view the configuration of formatting options.
239   ```ts
240   let options: intl.RelativeTimeFormatInputOptions = relativeTimeFormat.resolvedOptions();
241   ```
242
243**Relative Time Formatting Options**
244
245The following uses the relative time **one day ago** and locale IDs **fr-FR** and **en-GB** as an example to show different values of [RelativeTimeFormatInputOptions](../reference/apis-localization-kit/js-apis-intl.md#relativetimeformatinputoptions8) and corresponding display effects.
246
247**Table 11** Numeric representation (numeric)
248
249| Value  | Description                                         | Display Effect (fr-FR)| Display Effect (en-GB)|
250| ------ | -------------------------------------------- | -------------- | --------------- |
251| always | Use of a number to indicate the relative time                        | il y a 1 jour  | 1 day ago       |
252| auto   | Use of a phrase or value based on the locale ID to indicate the relative time| hier           | yesterday       |
253
254**Table 12** Relative time style (style)
255
256| Value  | Description                 | Display Effect (fr-FR)| Display Effect (en-GB)|
257| ------ | -------------------- | -------------- | --------------  |
258| long   | Long relative time display  | il y a 1 jour  | 1 day ago       |
259| short  | Short relative time display  | il y a 1 j     | 1 day ago       |
260| narrow | Narrow relative time display| -1 j           | 1 day ago       |
261
262
263**Development Example**
264```ts
265// Import the intl module.
266import { intl } from '@kit.LocalizationKit';
267
268// Display the relative time.
269let relativeTimeFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB');
270let formattedRelativeTime: string = relativeTimeFormat.format(-1, 'day'); // formattedRelativeTime = '1 day ago'
271
272// Display the relative time in a conversational style.
273let numericAutoFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB', { numeric: 'auto' });
274formattedRelativeTime = numericAutoFormat.format(-1, 'day'); // formattedRelativeTime = 'yesterday'
275
276// Use the narrow style for certain languages.
277let longFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('fr-FR'); // The default style is long.
278formattedRelativeTime = longFormat.format(-1, 'day'); // formattedRelativeTime = 'il y a 1 jour'
279let narrowFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('fr-FR', { style: 'narrow' });
280formattedRelativeTime = narrowFormat.format(-1, 'day'); // formattedRelativeTime = '-1 j'
281
282// Display the custom relative time for the specified locale.
283let partFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB', { style: 'long' });
284// parts = [{type: 'literal', value: 'in'}, {type: 'integer', value: 1, unit: 'day'}, {type: 'literal', value: 'day'}]
285let parts: object[] = partFormat.formatToParts(1, 'day');
286
287// Obtain the formatting options of RelativeTimeFormat.
288let resolvedFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB', { numeric: 'auto' });
289let options: intl.RelativeTimeFormatResolvedOptions = resolvedFormat.resolvedOptions();
290let numeric: string = options.numeric; // numeric = 'auto'
291```
292<!--no_check-->