Created
April 3, 2023 15:06
-
-
Save pdehaan/b7c731e3cf2bf526723ced61aecdaf98 to your computer and use it in GitHub Desktop.
Date parsing for fun ~and profit~
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const $classes = ` | |
Mon Apr 3 7pm-10pm (PDT) | |
Mon Apr 10 7pm-10pm | |
Mon Apr 17 7pm-10pm | |
Mon Apr 24 7pm-10pm | |
$120 USD, 8 (of 8) enrolled | |
`; | |
const classes = $classes.split("\n").filter(Boolean); | |
const priceEnrolled = classes.pop(); | |
for (const c of classes) { | |
// TODO: Is this always "PDT" or is it sometimes "PST"? | |
const dateParts = c.replace(/\s\(PDT\)$/i, "").trim().split(" "); | |
let [startTime, endTime] = dateParts.pop().split("-"); | |
const [, month, day, year=2023] = dateParts; | |
const dateString = [month, day, year].join(" "); | |
startTime = new Date(Date.parse(`${dateString} ${isoTime(startTime)}`)); | |
endTime = new Date(Date.parse(`${dateString} ${isoTime(endTime)}`)); | |
console.log({ | |
start: startTime.toISOString(), | |
end: endTime.toISOString(), | |
}); | |
} | |
function cleanTime(timeString) { | |
if (timeString.includes(":")) { | |
return timeString; | |
} | |
return timeString.replace(/^(\d+)(am|pm)$/i, "$1:00$2"); | |
} | |
function isoTime(timeString) { | |
timeString = cleanTime(timeString); | |
let { hour, minute, ampm } = /^(?<hour>\d+):(?<minute>\d{2})(?<ampm>(am|pm))$/i.exec(timeString).groups; | |
if (ampm === "pm") { | |
hour = (parseInt(hour, 10) + 12) % 24; | |
} | |
return `${hour}:${minute}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment