Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/date_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,11 @@ export function safeDateFormat(
return (date && formatDate(date, formatStr, locale)) || "";
}

/**
* Used as a delimiter to separate two dates when formatting a date range
*/
export const DATE_RANGE_SEPARATOR = " - ";

/**
* Safely formats a date range.
*
Expand All @@ -243,7 +248,7 @@ export function safeDateRangeFormat(
const formattedStartDate = safeDateFormat(startDate, props);
const formattedEndDate = endDate ? safeDateFormat(endDate, props) : "";

return `${formattedStartDate} - ${formattedEndDate}`;
return `${formattedStartDate}${DATE_RANGE_SEPARATOR}${formattedEndDate}`;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
type HighlightDate,
type HolidayItem,
KeyType,
DATE_RANGE_SEPARATOR,
} from "./date_utils";
import PopperComponent from "./popper_component";
import Portal from "./portal";
Expand Down Expand Up @@ -608,7 +609,7 @@ export default class DatePicker extends Component<

if (selectsRange) {
const [valueStart, valueEnd] = value
.split("-", 2)
.split(dateFormat.includes("-") ? DATE_RANGE_SEPARATOR : "-", 2)
.map((val) => val.trim());
const startDateNew = parseDate(
valueStart ?? "",
Expand Down
29 changes: 29 additions & 0 deletions src/test/datepicker_test.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3443,6 +3443,35 @@ describe("DatePicker", () => {
);
});

it("should parses date range with dashes correctly", () => {
const onChangeSpy = jest.fn();
const dateFormat = "yyyy-MM-dd";

const { container } = render(
<DatePicker
selectsRange
startDate={undefined}
endDate={undefined}
onChange={onChangeSpy}
dateFormat={dateFormat}
/>,
);

const input = safeQuerySelector<HTMLInputElement>(container, "input");
fireEvent.change(input, {
target: {
value: "2024-03-04 - 2024-05-06",
},
});
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(Array.isArray(onChangeSpy.mock.calls[0][0])).toBe(true);
const [startDate, endDate] = onChangeSpy.mock.calls[0][0];
expect(startDate).toBeTruthy();
expect(endDate).toBeTruthy();
expect(formatDate(startDate, dateFormat)).toBe("2024-03-04");
expect(formatDate(endDate, dateFormat)).toBe("2024-05-06");
});

it("should not fire onChange a second time if user edits text box without the parsing result changing", () => {
const onChangeSpy = jest.fn();
let instance: DatePicker | null = null;
Expand Down
Loading