x
1
2
3
4
5
6
7
8
<!-- Time --><time datetime="2024-12-02T16:52:28Z" data-local-time-target="time"></time><!-- Date --><time datetime="2024-12-02T16:52:28Z" data-local-time-target="date"></time><!-- Date Time --><time datetime="2024-12-02T16:52:28Z" data-local-time-target="datetime"></time>
1
2
3
4
5
6
7
8
<%# Time %><%= tag.time datetime: Time.current.iso8601, data: { local_time_target: "time" } %><%# Date %><%= tag.time datetime: Time.current.iso8601, data: { local_time_target: "date" } %><%# Date Time %><%= tag.time datetime: Time.current.iso8601, data: { local_time_target: "datetime" } %>
CSS is not required or multiple files are needed, check the notes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Controller } from "@hotwired/stimulus"export default class extends Controller { static targets = [ "time", "date", "datetime" ] initialize() { this.timeFormatter = new Intl.DateTimeFormat(undefined, { timeStyle: "short" }) this.dateFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "long" }) this.dateTimeFormatter = new Intl.DateTimeFormat(undefined, { timeStyle: "short", dateStyle: "short" }) } timeTargetConnected(target) { this.#formatTime(this.timeFormatter, target) } dateTargetConnected(target) { this.#formatTime(this.dateFormatter, target) } datetimeTargetConnected(target) { this.#formatTime(this.dateTimeFormatter, target) } #formatTime(formatter, target) { const dt = new Date(target.getAttribute("datetime")) target.textContent = formatter.format(dt) target.title = this.dateTimeFormatter.format(dt) }}
Initialization
<body data-controller="local-time"> <%= yield %></body>