Skip to content

Commit

Permalink
Fix off by one date selection issue (#7394)
Browse files Browse the repository at this point in the history
* Resolve #6115 by fixing deserialisation bug in DatePicker component

* update formatter to be more explicit about year month and day format style

* changeset
  • Loading branch information
gwyneplaine committed Mar 24, 2022
1 parent 5a43deb commit 5d96ee6
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/brave-emus-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-ui/fields': patch
---

Fixed off by one issue in date selection when using the timestamp field.
12 changes: 10 additions & 2 deletions design-system/packages/fields/src/DatePicker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export function useEventCallback<Func extends (...args: any) => any>(callback: F
return cb as any;
}

function deserializeDate(value: string): Date {
const [year, month, day] = value.split('-').map(el => parseInt(el, 10));
return new Date(year, month - 1, day);
}

export const DatePicker = ({
value,
onUpdate,
Expand Down Expand Up @@ -82,8 +87,11 @@ export const DatePicker = ({
[onUpdate, setOpen]
);

const selectedDay = new Date(value as string);
const formattedDate: DateInputValue = value ? formatDate(new Date(value)) : undefined;
// We **can** memoize this, but its a trivial operation
// and in the opinion of the author not really something to do
// before other more important performance optimisations
const selectedDay = deserializeDate(value);
const formattedDate: DateInputValue = value ? formatDate(selectedDay) : undefined;

return (
<Fragment>
Expand Down
4 changes: 3 additions & 1 deletion design-system/packages/fields/src/utils/dateFormatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export const formatDateType = (date: Date): DateType => {

// undefined means we'll use the user's locale
const formatter = new Intl.DateTimeFormat(undefined, {
dateStyle: 'short',
year: 'numeric',
month: '2-digit',
day: '2-digit',
});

export const formatDate = (date: Date): string => formatter.format(date);
Expand Down

0 comments on commit 5d96ee6

Please sign in to comment.