improved matching

This commit is contained in:
2023-02-20 19:11:40 +10:00
parent b50acd3b74
commit 4a6a65c5d2

View File

@@ -94,7 +94,10 @@ export class SMDate {
if (components[i].includes(":")) { if (components[i].includes(":")) {
time = components[i]; time = components[i];
components.splice(i, 1); components.splice(i, 1);
if (i < components.length && /^(am|pm)$/i.test(components[i])) { if (
i < components.length &&
/^(am?|a\.m\.|pm?|p\.m\.)$/i.test(components[i])
) {
time += " " + components[i].toUpperCase(); time += " " + components[i].toUpperCase();
components.splice(i, 1); components.splice(i, 1);
} }
@@ -102,6 +105,14 @@ export class SMDate {
} }
} }
if (components.every((v) => !isNaN(parseInt(v))) == false) {
return this;
}
if (components.length > 3) {
return this;
}
// Map the date components to the expected order based on the format // Map the date components to the expected order based on the format
const [day, month, year] = const [day, month, year] =
order[0] === "d" order[0] === "d"
@@ -114,6 +125,10 @@ export class SMDate {
parsedMonth: number = 0, parsedMonth: number = 0,
parsedYear: number = 0; parsedYear: number = 0;
if (year.length == 3 || year.length >= 5) {
return this;
}
if (day && day.length != 0 && month && month.length != 0) { if (day && day.length != 0 && month && month.length != 0) {
// Parse the day, month, and year components // Parse the day, month, and year components
parsedDay = parseInt(day.padStart(2, "0"), 10); parsedDay = parseInt(day.padStart(2, "0"), 10);
@@ -131,17 +146,31 @@ export class SMDate {
parsedMinutes: number = 0, parsedMinutes: number = 0,
parsedSeconds: number = 0; parsedSeconds: number = 0;
if (time) { if (time) {
const match = time.match(/(\d+)(?::(\d+))?(?::(\d+))? ?(AM|PM)?/i); const regEx = new RegExp(
if (match) { /^(\d+)(?::(\d+))?(?::(\d+))? ?(am?|a\.m\.|pm?|p\.m\.)?$/,
parsedHours = parseInt(match[1]); "i"
parsedMinutes = match[2] ? parseInt(match[2]) : 0; );
parsedSeconds = match[3] ? parseInt(match[3]) : 0; if (regEx.test(time)) {
if (match[4] && /pm/i.test(match[4])) { const match = time.match(regEx);
parsedHours += 12; if (match) {
} parsedHours = parseInt(match[1]);
if (match[4] && /am/i.test(match[4]) && parsedHours === 12) { parsedMinutes = match[2] ? parseInt(match[2]) : 0;
parsedHours = 0; parsedSeconds = match[3] ? parseInt(match[3]) : 0;
if (match[4] && /pm/i.test(match[4])) {
parsedHours += 12;
}
if (
match[4] &&
/am/i.test(match[4]) &&
parsedHours === 12
) {
parsedHours = 0;
}
} else {
return this;
} }
} else {
return this;
} }
} }
@@ -448,5 +477,3 @@ export class SMDate {
return result; return result;
} }
} }
console.log(new SMDate("").isValid());