Skip to content

Instantly share code, notes, and snippets.

@fractaledmind
Created July 9, 2023 18:47
Show Gist options
  • Save fractaledmind/2c7c8113b89dffffb8d69f3bcbf67f66 to your computer and use it in GitHub Desktop.
Save fractaledmind/2c7c8113b89dffffb8d69f3bcbf67f66 to your computer and use it in GitHub Desktop.
import { Controller } from "@hotwired/stimulus"
// use with Rails' `time_Tag` helper like so:
// <%= time_tag campaign.starts_at, campaign.starts_at.to_formatted_s(:short), data: { controller: "localized-time", localized_time_type_value: "datetime-short" } %>
export default class extends Controller {
static targets = [ ]
static values = {
type: String,
style: { type: String, default: 'medium' },
locale: { type: String, default: 'default' },
}
connect() {
let datetimeStr = this.element.getAttribute('datetime')
let options
if (this.typeValue == 'datetime') {
options = {dateStyle: this.styleValue, timeStyle: this.styleValue}
}
else if (this.typeValue == 'date') {
options = {dateStyle: this.styleValue}
}
else if (this.typeValue == 'time') {
options = {timeStyle: this.styleValue}
let current = new Date().toISOString()
let currentDate = current.split('T')[0]
datetimeStr = currentDate + 'T' + datetimeStr
}
else if (this.typeValue == 'datetime-short') {
options = {hourCycle: 'h24', day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit'}
}
else {
options = {}
}
const datetime = new Date(datetimeStr)
if (datetime instanceof Date && !!datetime.getDate()) {
this.element.textContent = datetime.toLocaleString(this.localeValue, options)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment