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

78 wiersze
2.2 KiB
TypeScript
Czysty Zwykły widok Historia

import { LitElement, property } from 'lit-element';
import { tag } from '../../internal/decorators';
2020-11-25 21:18:07 +00:00
/**
* @since 2.0
* @status stable
*/
@tag('sl-format-date')
2021-03-09 00:14:32 +00:00
export default class SlFormatDate extends LitElement {
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-03-06 17:01:39 +00:00
@property() date: Date | string = new Date();
2020-11-25 21:18:07 +00:00
/** The locale to use when formatting the date/time. */
2021-03-06 17:01:39 +00:00
@property() locale: string;
2020-11-25 21:18:07 +00:00
/** The format for displaying the weekday. */
2021-03-06 17:01:39 +00:00
@property() weekday: 'narrow' | 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The format for displaying the era. */
2021-03-06 17:01:39 +00:00
@property() era: 'narrow' | 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The format for displaying the year. */
2021-03-06 17:01:39 +00:00
@property() year: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the month. */
2021-03-06 17:01:39 +00:00
@property() month: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The format for displaying the day. */
2021-03-06 17:01:39 +00:00
@property() day: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the hour. */
2021-03-06 17:01:39 +00:00
@property() hour: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the minute. */
2021-03-06 17:01:39 +00:00
@property() minute: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the second. */
2021-03-06 17:01:39 +00:00
@property() second: 'numeric' | '2-digit';
2020-11-25 21:18:07 +00:00
/** The format for displaying the time. */
2021-03-06 17:01:39 +00:00
@property({ attribute: 'time-zone-name' }) timeZoneName: 'short' | 'long';
2020-11-25 21:18:07 +00:00
/** The time zone to express the time in. */
2021-03-06 17:01:39 +00:00
@property({ attribute: 'time-zone' }) timeZone: string;
2020-11-25 21:18:07 +00:00
/** When set, 24 hour time will always be used. */
2021-03-06 17:01:39 +00:00
@property({ attribute: 'hour-format' }) 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);
}
}
declare global {
interface HTMLElementTagNameMap {
'sl-format-date': SlFormatDate;
}
}