Last active
April 1, 2023 02:33
-
-
Save pdehaan/94393abbe9241c23a89cfb7f3aec8b00 to your computer and use it in GitHub Desktop.
Date string parsing w/ Luxon
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 { DateTime } = require("luxon"); | |
const start = parseDateTime("Thu Apr 13", "1pm"); | |
const end = parseDateTime("Mon Dec 19 2022", "4pM"); | |
console.log(`${start} -- ${end}`); | |
function parseDateTime(dateString, timeString) { | |
const CURR_YEAR = new Date().getFullYear(); | |
const DATE_FORMAT = /* ccc */ "LLL d yyyy"; | |
const TIME_FORMAT = "h:mma"; | |
const [, month, day, year = CURR_YEAR] = dateString.split(" ", 4); | |
if (!timeString.includes(":")) { | |
timeString = timeString.replace(/^(\d+)(am|pm)$/i, "$1:00$2"); | |
} | |
return DateTime.fromFormat( | |
`${month} ${day} ${year} ${timeString}`, | |
`${DATE_FORMAT} ${TIME_FORMAT}` | |
).toJSDate(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment