Last active
May 22, 2017 19:14
-
-
Save kmaida/1b7c713b08ca09af83b4f4e208641fd1 to your computer and use it in GitHub Desktop.
Date (mm/dd/yyyy) and time (hh:mm AM/PM) strings to JS Date
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
// MM/DD/YYYY, M/D/YYYY | |
const dateRegex = new RegExp(/^(\d{2}|\d{1})\/(\d{2}|\d{1})\/\d{4}$/); | |
// HH:MM am/pm, HH:MM AM/PM | |
const timeRegex = new RegExp(/\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))/); | |
// Convert date and time strings to a Date object | |
function stringsToDate(dateStr, timeStr) { | |
if (!dateRegex.test(dateStr) || !timeRegex.test(timeStr)) { | |
return null; | |
} | |
const timeArr = timeStr.split(/[\s:]+/); | |
const date = new Date(dateStr); | |
let hour = parseInt(timeArr[0], 10); | |
const min = parseInt(timeArr[1], 10); | |
const pm = timeArr[2].toLowerCase() === 'pm'; | |
if (!pm && hour === 12) { | |
hour = 0; | |
} | |
if (pm && hour < 12) { | |
hour += 12; | |
} | |
date.setHours(hour); | |
date.setMinutes(min); | |
return date; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment