import { LightningElement, api } from "lwc"; import { convertForDaylightSavings } from "dxUtils/dates"; import { formattedDateDay, formattedDateHour, formattedDateMinute, formattedDateMonth, formattedDateOptions, formattedDateSecond, formattedDateTimeZoneName, formattedDateWeekday, formattedDateYear } from "typings/custom"; import { DateTime } from "luxon"; export default class FormattedDateTime extends LightningElement { @api weekday: formattedDateWeekday; @api year: formattedDateYear; @api month: formattedDateMonth; @api day: formattedDateDay; @api hour: formattedDateHour; @api minute: formattedDateMinute; @api second: formattedDateSecond; @api timeZoneName: formattedDateTimeZoneName; @api set value(value) { if (!value) { console.error("Value provided to FormattedDateTime is invalid"); return; } this._unformattedDate = convertForDaylightSavings(value).toJSDate(); if (this._unformattedDate.toString() === "Invalid Date") { // this is a fix for Safari since it doesn't support date strings with 'yyyy/mm/dd' patterns this._unformattedDate = new Date(value.replace(/-/g, "/")); } } get value() { const options = this.getOptions(); this._formattedDate = this.formatDate( this._unformattedDate, options as any ); return this._formattedDate; } private _formattedDate!: string; private _unformattedDate!: Date; formatDate(unformattedDate: Date, options: formattedDateOptions) { const locale = navigator.language; let formattedDateTime = DateTime.fromISO(unformattedDate?.toISOString()) .setLocale(locale) .toLocaleString(options as any); formattedDateTime = this.updateDayPeriodFormatting(formattedDateTime); return formattedDateTime; } updateDayPeriodFormatting(formattedDateTime: string) { return formattedDateTime .replace(/(\b|\d+)AM\b/, (_, part1) => `${part1}a.m.`) .replace(/(\b|\d+)PM\b/, (_, part1) => `${part1}p.m.`); } getOptions() { return { weekday: this.weekday || undefined, year: this.year || undefined, month: this.month || undefined, day: this.day || undefined, hour: this.hour || undefined, minute: this.minute || undefined, second: this.second, timeZoneName: this.timeZoneName || undefined }; } }