shoelace/src/components/format-date/format-date.ts

88 wiersze
2.1 KiB
TypeScript
Czysty Zwykły widok Historia

2021-02-26 14:09:13 +00:00
import { Shoemaker } from '@shoelace-style/shoemaker';
2020-11-25 21:18:07 +00:00
/**
* @since 2.0
* @status stable
*/
2021-02-26 14:09:13 +00:00
export default class SlFormatDate extends Shoemaker {
static tag = 'sl-format-date';
static props = [
'date',
'locale',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName',
'timeZone',
'hourFormat'
];
2020-11-25 21:18:07 +00:00
/** The date/time to format. If not set, the current date and time will be used. */
2021-02-26 14:09:13 +00:00
date: Date | string = new Date();
2020-11-25 21:18:07 +00:00
/** The locale to use when formatting the date/time. */
2021-02-26 14:09:13 +00:00
locale: string;
2020-11-25 21:18:07 +00:00
/** The format for displaying the weekday. */
2021-02-26 14:09:13 +00:00
weekday: 'narrow' | 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The format for displaying the era. */
2021-02-26 14:09:13 +00:00
era: 'narrow' | 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The format for displaying the year. */
2021-02-26 14:09:13 +00:00
year: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the month. */
2021-02-26 14:09:13 +00:00
month: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The format for displaying the day. */
2021-02-26 14:09:13 +00:00
day: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the hour. */
2021-02-26 14:09:13 +00:00
hour: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the minute. */
2021-02-26 14:09:13 +00:00
minute: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the second. */
2021-02-26 14:09:13 +00:00
second: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the time. */
2021-02-26 14:09:13 +00:00
timeZoneName: 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The time zone to express the time in. */
2021-02-26 14:09:13 +00:00
timeZone: string;
2020-11-25 21:18:07 +00:00
/** When set, 24 hour time will always be used. */
2021-02-26 14:09:13 +00:00
hourFormat: 'auto' | '12' | '24' = 'auto';
2020-11-25 21:18:07 +00:00
render() {
const date = new Date(this.date);
const hour12 = this.hourFormat === 'auto' ? undefined : this.hourFormat === '12';
// Check for an invalid date
if (isNaN(date.getMilliseconds())) {
return;
}
return new Intl.DateTimeFormat(this.locale, {
weekday: this.weekday,
era: this.era,
year: this.year,
month: this.month,
day: this.day,
hour: this.hour,
minute: this.minute,
second: this.second,
timeZoneName: this.timeZoneName,
timeZone: this.timeZone,
hour12: hour12
}).format(date);
}
}