尝试重构/优化解析日期范围或日期的现有方法:
const parseDateRange = (range: string): Date | null => {
if (!range?.length) {
return null;
}
// Handle "MM/YYYY" format
if (/^\d{1,2}\/\d{4}$/.test(range)) {
const [month, year] = range.split('/').map(Number);
if (!isNaN(month) && !isNaN(year)) {
return new Date(year, month - 1);
}
}
// Handle "MM/DD/YYYY-MM/DD/YYYY" format
const startDateString = range.slice(0, range.indexOf('-')).trim();
const startDate = new Date(startDateString);
if (!isNaN(startDate.getTime())) {
return startDate;
}
return null;
};
我可能可以在这里使用类似的类型:
type Split<S extends string, D extends string> =
string extends S ? string[] :
S extends '' ? [] :
S extends `${infer T}${D}${infer U}` ? [T, U]:
[S];
希望建议我如何利用它或类似的方法来解析此处的分隔日期范围类型。
我确信您可以为此使用不同的库,例如
Moment.js
和date-fns
,但我只是假设您在某些特定情况下需要它,在这种情况下,您可以使用我在下面提供的代码来解决这个问题。
type Split<S extends string, D extends string> = string extends S
? string[]
: S extends ""
? []
: S extends `${infer T}${D}${infer U}`
? [T, U]
: [S];
const parseDateRange = (range: string): string | null => {
if (!range?.length) {
return null;
}
// Handle "MM/YYYY" format
const mmYYYYMatch = /^(\d{1,2})\/(\d{4})$/.exec(range);
if (mmYYYYMatch) {
const [_, month, year] = mmYYYYMatch.map(Number);
if (month && year) {
let new_date = new Date(year, month - 1);
return new_date.toUTCString();
}
}
// Handle "MM/DD/YYYY-MM/DD/YYYY" format
const [start, end] = range.split("-").map((date) => date.trim());
const startDate = new Date(start);
const endDate = new Date(end);
if (!isNaN(startDate.getTime())) {
return startDate.toUTCString(); // Optionally, handle `endDate` if needed.
}
return null;
};
// Example usage
console.log(parseDateRange("08/2024")); // Expected output: Date object for August 2024
console.log(parseDateRange("08/12/2024-08/13/2024")); // Expected output: Date object for August 12, 2024
console.log(parseDateRange("Invalid input")); // Expected output: null
// convert from Z U T C to local time
const date = new Date("2024-08-12T00:00:00Z");
console.log(date.toLocaleString()); // Expected output: Local time for August 12, 2024
结果
Wed, 31 Jul 2024 23:00:00 GMT
Sun, 11 Aug 2024 23:00:00 GMT
null
8/12/2024, 1:00:00 AM