From 34feb495faf5afc21e6d76093fb7687cd1bfae2a Mon Sep 17 00:00:00 2001 From: Alexandra Goff Date: Thu, 5 Dec 2024 10:28:43 -0500 Subject: [PATCH] fix: put timezone offset into date --- components/templates/NewsPage/index.tsx | 4 ---- lib/utils.js | 22 ++++++++++++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/components/templates/NewsPage/index.tsx b/components/templates/NewsPage/index.tsx index 8898271d..7dd30a7e 100644 --- a/components/templates/NewsPage/index.tsx +++ b/components/templates/NewsPage/index.tsx @@ -34,7 +34,6 @@ const NewsPage: FunctionComponent<{ subtitle, images, videos, - release_date: date, links, contacts, } = release; @@ -47,7 +46,6 @@ const NewsPage: FunctionComponent<{ releaseDescription: description ? sanitizeHtml(description) : undefined, links: links ? sanitizeHtml(links) : links, contacts, - date, images, videos, }; @@ -75,7 +73,6 @@ const NewsPage: FunctionComponent<{ subtitle, images, videos, - release_date: date, more_information: moreInformation, links, contacts, @@ -93,7 +90,6 @@ const NewsPage: FunctionComponent<{ : undefined, links: links ? sanitizeHtml(links) : links, contacts, - date, images, videos, }; diff --git a/lib/utils.js b/lib/utils.js index 06392054..0049bf51 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -179,17 +179,31 @@ function dateWoTimezone(iso) { return new Date(iso.slice(0, -6)); } -export const useDateString = (date, isShort = false) => { +export const useDateString = (date, options = {}) => { + const { isShort = false, isCraftDate = true } = options; const localeInfo = useGlobalData("localeInfo"); const locale = localeInfo.language || fallbackLng; const newDate = new Date(date); - const options = { + + /** + * Craft dates are stored in UTC with the timezone applied as an hours offset + * The user's timezone offset needs to be removed to restore the original date + * + * https://craftcms.com/docs/4.x/time-fields.html#converting-from-a-date-field + */ + if (isCraftDate) { + newDate.setTime( + newDate.getTime() + newDate.getTimezoneOffset() * 60 * 1000 + ); + } + const localeOptions = { year: "numeric", - month: `${isShort ? "short" : "long"}`, + month: isShort ? "short" : "long", day: "numeric", }; - let dateString = newDate.toLocaleString(locale, options); + let dateString = newDate.toLocaleString(locale, localeOptions); isShort && (dateString = dateString.replace(",", "")); + return dateString; };