Skip to content

Commit

Permalink
fix: fixed date fields prefilling with wrong dates in some timezones
Browse files Browse the repository at this point in the history
  • Loading branch information
Fredx87 committed Oct 25, 2024
1 parent 4f01052 commit 67fd377
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions src/modules/new-request-form/fields/DatePicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import { Span } from "@zendeskgarden/react-typography";
import type { Field } from "../data-types";
import type { ChangeEventHandler } from "react";
import { useState } from "react";
import { useMemo, useState } from "react";

interface DatePickerProps {
field: Field;
Expand All @@ -29,7 +29,26 @@ export function DatePicker({
value ? new Date(value as string) : undefined
);

const formatDate = (value: Date | undefined) => {
const dateTimeFormat = useMemo(
() =>
new Intl.DateTimeFormat(locale, {
month: "long",
day: "numeric",
year: "numeric",
timeZone: "UTC",
}),
[locale]
);

/* Formats the date using the UTC time zone to prevent timezone-related issues.
* By creating a new Date object with only the date, the time defaults to 00:00:00 UTC.
* This avoids date shifts that can occur if formatted with the local time zone, as Garden does by default.
*/
const formatDateInput = (date: Date) => {
return dateTimeFormat.format(date);
};

const formatDateValue = (value: Date | undefined) => {
if (value === undefined) {
return "";
}
Expand All @@ -43,7 +62,7 @@ export function DatePicker({
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0)
) as Date;
setDate(newDate);
const dateString = formatDate(newDate);
const dateString = formatDateValue(newDate);
if (dateString !== undefined) {
onChange(dateString);
}
Expand All @@ -66,7 +85,12 @@ export function DatePicker({
{description && (
<Hint dangerouslySetInnerHTML={{ __html: description }} />
)}
<GardenDatepicker value={date} onChange={handleChange} locale={locale}>
<GardenDatepicker
value={date}
onChange={handleChange}
formatDate={formatDateInput}
locale={locale}
>
<Input
required={required}
lang={locale}
Expand All @@ -75,7 +99,7 @@ export function DatePicker({
/>
</GardenDatepicker>
{error && <Message validation="error">{error}</Message>}
<input type="hidden" name={name} value={formatDate(date)} />
<input type="hidden" name={name} value={formatDateValue(date)} />
</GardenField>
);
}

0 comments on commit 67fd377

Please sign in to comment.