|
1 | 1 | import { isIE } from '../core/utils';
|
2 | 2 | import { DatePart, DatePartInfo } from '../directives/date-time-editor/date-time-editor.common';
|
| 3 | +import { formatDate, FormatWidth, getLocaleDateFormat } from '@angular/common'; |
3 | 4 |
|
4 | 5 | /**
|
5 | 6 | * This enum is used to keep the date validation result.
|
@@ -48,7 +49,7 @@ export abstract class DatePickerUtil {
|
48 | 49 |
|
49 | 50 |
|
50 | 51 | /**
|
51 |
| - * TODO: Unit tests for all public methods. |
| 52 | + * TODO: (in issue #6483) Unit tests and docs for all public methods. |
52 | 53 | */
|
53 | 54 |
|
54 | 55 |
|
@@ -147,6 +148,38 @@ export abstract class DatePickerUtil {
|
147 | 148 | return DatePickerUtil.getMask(parts);
|
148 | 149 | }
|
149 | 150 |
|
| 151 | + public static formatDate(value: number | Date, format: string, locale: string, timezone?: string): string { |
| 152 | + let formattedDate: string; |
| 153 | + try { |
| 154 | + formattedDate = formatDate(value, format, locale, timezone); |
| 155 | + } catch { |
| 156 | + this.logMissingLocaleSettings(locale); |
| 157 | + const formatter = new Intl.DateTimeFormat(locale); |
| 158 | + formattedDate = formatter.format(value); |
| 159 | + } |
| 160 | + |
| 161 | + return formattedDate; |
| 162 | + } |
| 163 | + |
| 164 | + public static getLocaleDateFormat(locale: string, displayFormat?: string): string { |
| 165 | + const formatKeys = Object.keys(FormatWidth) as (keyof FormatWidth)[]; |
| 166 | + const targetKey = formatKeys.find(k => k.toLowerCase() === displayFormat?.toLowerCase().replace('date', '')); |
| 167 | + if (!targetKey) { |
| 168 | + // if displayFormat is not shortDate, longDate, etc. |
| 169 | + // or if it is not set by the user |
| 170 | + return displayFormat; |
| 171 | + } |
| 172 | + let format: string; |
| 173 | + try { |
| 174 | + format = getLocaleDateFormat(locale, FormatWidth[targetKey]); |
| 175 | + } catch { |
| 176 | + this.logMissingLocaleSettings(locale); |
| 177 | + format = DatePickerUtil.getDefaultInputFormat(locale); |
| 178 | + } |
| 179 | + |
| 180 | + return format; |
| 181 | + } |
| 182 | + |
150 | 183 | public static isDateOrTimeChar(char: string): boolean {
|
151 | 184 | return DATE_CHARS.indexOf(char) !== -1 || TIME_CHARS.indexOf(char) !== -1;
|
152 | 185 | }
|
@@ -303,6 +336,11 @@ export abstract class DatePickerUtil {
|
303 | 336 | return _value.getTime() < _minValue.getTime();
|
304 | 337 | }
|
305 | 338 |
|
| 339 | + private static logMissingLocaleSettings(locale: string): void { |
| 340 | + console.warn(`Missing locale data for the locale ${locale}. Please refer to https://angular.io/guide/i18n#i18n-pipes`); |
| 341 | + console.warn('Using default browser locale settings.'); |
| 342 | + } |
| 343 | + |
306 | 344 | private static ensureLeadingZero(part: DatePartInfo) {
|
307 | 345 | switch (part.type) {
|
308 | 346 | case DatePart.Date:
|
|
0 commit comments