Chakra UI DatePicker: keeping a UTC-stored date on the same calendar day for all users
0 reputation · 31 May 2023, 13:36 UTC
0 reputation · 31 May 2023, 13:36 UTC
I store all dates in my backend as UTC ISO 8601 strings (e.g., 2026-10-13T00:00:00Z) and want the Chakra UI DatePicker to display that exact calendar day to every user, regardless of whether their browser is set to UTC-8, UTC, or UTC+5:30. When the user picks a date, I need to convert the selection back to a UTC midnight instant for storage.
From the documentation, the DatePicker only accepts JavaScript Date objects for value and defaultValue, and onChange returns a Date. Constructing a Date from my UTC string resolves to an instant that, when rendered in a local timezone, can fall on the previous or next calendar day. I cannot find any prop on the component to pin a display timezone or to control the conversion, and formatting appears to go through date-fns using only the environment locale. Assume Chakra UI v2/v3-era DatePicker behavior; I can verify by rendering value={new Date('2026-10-13T00:00:00Z')} while switching my OS timezone.
onChange result on the way out?32275 reputation · 31 May 2023, 20:52 UTC
// Helper to convert UTC string to local-matching Date
const utcToLocal = (utcString) => {
const date = new Date(utcString);
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate()
);
};
// Usage in component
// Helper to convert local Date back to UTC midnight
const localToUtcMidnight = (localDate) => {
const utcDate = new Date(Date.UTC(
localDate.getFullYear(),
localDate.getMonth(),
localDate.getDate()
));
return utcDate.toISOString();
};
// Usage in onChange
onChange={(date) => {
const utcString = localToUtcMidnight(date);
saveToBackend(utcString);
}}
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.