Skip to content

Instantly share code, notes, and snippets.

@dorianmariecom
Created April 12, 2021 21:36
Show Gist options
  • Save dorianmariecom/64d061239cb090f2e4ea4a94c6db44ae to your computer and use it in GitHub Desktop.
Save dorianmariecom/64d061239cb090f2e4ea4a94c6db44ae to your computer and use it in GitHub Desktop.
import { Controller } from "stimulus"
import strftime from "strftime"
import { capitalize } from "src/helpers"
const LOCALIZED_STRFTIME = {
en: strftime.localizeByIdentifier("en_US"),
fr: strftime.localizeByIdentifier("fr_FR"),
es: strftime.localizeByIdentifier("es_MX"),
it: strftime.localizeByIdentifier("it_IT"),
de: strftime.localizeByIdentifier("de_DE"),
pt: strftime.localizeByIdentifier("pt_BR"),
}
const FORMATS = {
long: {
en: "%A %-d %B %Y at %l:%M%P",
fr: "%A %-d %B %Y à %Hh%M",
es: "%A %-d de %B de %Y %H:%M",
it: "%A %-d %B %Y %H:%M",
de: "%A, %-d. %B %Y, %H:%M Uhr",
pt: "%A, %-d de %B de %Y, %H:%Mh",
},
short: {
en: "%a %e %b %l:%M%P",
fr: "%a %e %b %kh%M",
es: "%a %e %b %k:%M",
it: "%a %e %b %H:%M",
de: "%a, %e. %b, %H:%M Uhr",
pt: "%a, %e de %b %H:%M hs",
},
}
export default class extends Controller {
connect() {
const locale = this.data.get("locale")
const format = this.data.get("format")
const datetime = new Date(this.data.get("datetime"))
const localizedStrftime = LOCALIZED_STRFTIME[locale]
if (!localizedStrftime) return
this.element.innerText = capitalize(
localizedStrftime(FORMATS[format][locale], datetime)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment