Skip to content

Instantly share code, notes, and snippets.

@kmaida
Last active May 22, 2017 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmaida/1b7c713b08ca09af83b4f4e208641fd1 to your computer and use it in GitHub Desktop.
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
// 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