better matching

This commit is contained in:
2024-08-26 12:52:55 -06:00
parent 884e465df6
commit cafe04faf6
15 changed files with 232 additions and 33 deletions

View File

@@ -0,0 +1,19 @@
import { describe, it, expect } from "vitest";
import { getDateFromString } from "../timeUtils";
describe("Can properly handle expected date formats", () => {
it("can use AM/PM dates", () =>{
const dateString = "8/27/2024 1:00:00AM"
const dateObject = getDateFromString(dateString)
expect(dateObject).not.toBeUndefined()
})
it("can use 24 hour dates", () =>{
const dateString = "8/27/2024 23:95:00"
const dateObject = getDateFromString(dateString)
expect(dateObject).not.toBeUndefined()
})
})

View File

@@ -1,24 +1,39 @@
export const getDateFromString = (value: string) => {
// may need to check for other formats
const validDateRegex =
/\d{2}\/\d{2}\/\d{4} [0-2][0-9]:[0-5][0-9]:[0-5][0-9]/;
// Updated regex to match both formats: "MM/DD/YYYY HH:mm:ss" and "M/D/YYYY h:mm:ss AM/PM"
const validDateRegex = /^\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}:\d{2}(?:\s?[APap][Mm])?$/;
if (!validDateRegex.test(value)) {
console.log("invalid date format", value);
return undefined;
}
const [datePart, timePart] = value.split(" ");
const [datePart, timePartWithMeridian] = value.split(" ");
const [day, month, year] = datePart.split("/").map(Number);
let [timePart, meridian] = timePartWithMeridian.split(" ");
const [hours, minutes, seconds] = timePart.split(":").map(Number);
const date = new Date(year, month - 1, day, hours, minutes, seconds);
let adjustedHours = hours;
if (meridian) {
meridian = meridian.toUpperCase();
if (meridian === "PM" && hours < 12) {
adjustedHours += 12;
} else if (meridian === "AM" && hours === 12) {
adjustedHours = 0;
}
}
const date = new Date(year, month - 1, day, adjustedHours, minutes, seconds);
if (isNaN(date.getTime())) {
console.log("could not parse time out of value", value);
return undefined;
}
return date;
};
export const verifyDateStringOrUndefined = (
value: string
): string | undefined => {