Skip to content

Commit

Permalink
Do not include timezone in datepickers only displaying date
Browse files Browse the repository at this point in the history
We must not include timezone information when storing date
columns. It would lead to wrongly stored dates otherwise.

(cherry picked from commit 3575840)
  • Loading branch information
tvdeyen committed Mar 5, 2024
1 parent 57c9414 commit fe52b37
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
23 changes: 17 additions & 6 deletions app/javascript/alchemy_admin/components/datepicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,37 @@ class Datepicker extends AlchemyHTMLElement {
}

afterRender() {
this.flatpickr = flatpickr(
this.getElementsByTagName("input")[0],
this.flatpickrOptions
)
}

disconnected() {
this.flatpickr.destroy()
}

get flatpickrOptions() {
const enableTime = /time/.test(this.inputType)
const options = {
// alchemy_i18n supports `zh_CN` etc., but flatpickr only has two-letter codes (`zh`)
locale: currentLocale().slice(0, 2),
altInput: true,
altFormat: translate(`formats.${this.inputType}`),
altInputClass: "flatpickr-input",
dateFormat: "Z",
enableTime: /time/.test(this.inputType),
enableTime,
noCalendar: this.inputType === "time",
time_24hr: translate("formats.time_24hr"),
onValueUpdate(_selectedDates, _dateStr, instance) {
instance.element.closest("alchemy-element-editor")?.setDirty()
}
}

this.flatpickr = flatpickr(this.getElementsByTagName("input")[0], options)
}
if (enableTime) {
options.dateFormat = "Z"
}

disconnected() {
this.flatpickr.destroy()
return options
}
}

Expand Down
30 changes: 30 additions & 0 deletions spec/javascript/alchemy_admin/components/datepicker.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,34 @@ describe("alchemy-datepicker", () => {
expect(document.querySelector(".flatpickr-calendar")).toBeNull()
})
})

it("should include timezone for time inputs", () => {
const html = `
<alchemy-datepicker input-type="time">
<input type="text">
</alchemy-datepicker>
`
component = renderComponent("alchemy-datepicker", html)
expect(component.flatpickrOptions.dateFormat).toEqual("Z")
})

it("should include timezone for datetime inputs", () => {
const html = `
<alchemy-datepicker input-type="datetime">
<input type="text">
</alchemy-datepicker>
`
component = renderComponent("alchemy-datepicker", html)
expect(component.flatpickrOptions.dateFormat).toEqual("Z")
})

it("should not include timezone for date inputs", () => {
const html = `
<alchemy-datepicker input-type="date">
<input type="text">
</alchemy-datepicker>
`
component = renderComponent("alchemy-datepicker", html)
expect(component.flatpickrOptions.dateFormat).toBeUndefined()
})
})

0 comments on commit fe52b37

Please sign in to comment.