Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Title of the document</title> </head> <body> <time-format id="elem" hour="numeric" minute="numeric" second="numeric"></time-format> <script> class TimeFormatted extends HTMLElement { render() { // ( 1 ) let dateTime = new Date(this.getAttribute('datetime') || Date.now()); this.innerHTML = new Intl.DateTimeFormat("default", { y: this.getAttribute('year') || undefined, m: this.getAttribute('month') || undefined, d: this.getAttribute('day') || undefined, h: this.getAttribute('hour') || undefined, m: this.getAttribute('minute') || undefined, s: this.getAttribute('second') || undefined, timeZoneName: this.getAttribute('time-zone-name') || undefined, }).format(dateTime); } connectedCallback() { // (2) if(!this.rendered) { this.render(); this.rendered = true; } } static get observedAttributes() { // (3) return ['datetime', 'year', 'month', 'day', 'hour', 'minute', 'second', 'time-zone-name']; } attributeChangedCallback(name, oldValue, newValue) { // (4) this.render(); } } customElements.define("time-format", TimeFormatted); setInterval(() => elem.setAttribute('datetime', new Date()), 1000); // (5) customElements.define("time-formatted", TimeFormatted); // (2) </script> </body> </html>