Skip to content

Commit

Permalink
[Issue #2736] refactor dateUtils to use dayJS (#3892)
Browse files Browse the repository at this point in the history
  • Loading branch information
karinamzalez authored Feb 21, 2025
1 parent 1bd3ffb commit 8dcddc9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 22 deletions.
1 change: 1 addition & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

### Running the app locally

For version 0.1.0, please install and use node <= v22.13.0.
From the `/frontend` directory:

1. Install dependencies
Expand Down
26 changes: 7 additions & 19 deletions frontend/src/utils/dateUtil.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,22 @@
import dayjs from "dayjs";
import advancedFormat from "dayjs/plugin/advancedFormat";
import customParseFormat from "dayjs/plugin/customParseFormat";
import localizedFormat from "dayjs/plugin/localizedFormat";
import timezone from "dayjs/plugin/timezone";

dayjs.extend(timezone);
dayjs.extend(advancedFormat);
dayjs.extend(customParseFormat);
dayjs.extend(localizedFormat);
dayjs.extend(timezone);

// Convert "2024-02-21" to "February 21, 2024"
export function formatDate(dateStr: string | null): string {
if (!dateStr || dateStr.length !== 10) {
console.warn("invalid date string provided for parse");
return "";
}

const parts = dateStr.split("-");

if (parts.length !== 3) {
if (!dateStr || !dayjs(dateStr, "YYYY-MM-DD", true).isValid()) {
console.warn("invalid date string provided for parse");
return "";
}

const [year, month, day] = parts.map(Number);
// Create a new Date object using the local time
const date = new Date(year, month - 1, day);

const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "long",
day: "numeric",
};
return date.toLocaleDateString("en-US", options);
return dayjs(dateStr).format("LL");
}

export const getConfiguredDayJs = () => dayjs;
6 changes: 3 additions & 3 deletions frontend/tests/utils/dateUtil.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ describe("formatDate", () => {
beforeEach(() => {
jest.spyOn(console, "warn").mockImplementation(identity);
});
it("returns empty string when an incorrectly formatted string is passed", () => {
it("returns empty string when an invalid date string is passed", () => {
expect(formatDate(null)).toEqual("");
expect(formatDate("")).toEqual("");
expect(formatDate("Wednesday")).toEqual("");
expect(formatDate("20241010")).toEqual("");
expect(formatDate(Date.now().toString())).toEqual("");
expect(formatDate("20241010")).toBe("");
expect(formatDate("24-10-10")).toEqual("");
expect(formatDate(Date.now().toString())).toEqual("");
});

it("returns a human readable string for properly formatted dates", () => {
Expand Down

0 comments on commit 8dcddc9

Please sign in to comment.