Skip to content

Instantly share code, notes, and snippets.

@bhavyaw
Created June 4, 2016 14:41
Show Gist options
  • Save bhavyaw/4b75fc6273e40ff573221712464ddb8f to your computer and use it in GitHub Desktop.
Save bhavyaw/4b75fc6273e40ff573221712464ddb8f to your computer and use it in GitHub Desktop.
Parses Time String to JavaScript Date Object
/**
* Parsing Time in String to a Date Obj
* @param timeString - time in String
* --> Acceptable Times -
* 1,01,10,011,101,110,0111,1011,
* With AM/PM - 1p,01p,10p
*
* @returns tempDateObj {Date} - Date Object that represents time String
*/
function parseTimeString(timeString) {
var hour, minute,pm,
tempDateObj = new Date(),
num = timeString.replace(/[^0-9]/g, ''),
numLength = num && num.length;
var stringContainsLetterP = timeString.match(/p/i) !== null;
var stringContainsLetterA = timeString.match(/a/i) !== null;
//setting tempDateObj to Mid-Night
tempDateObj.setHours(0,0,0,0);
// Parse for hour and minute
switch(true) {
case numLength >= 4:
hour = parseInt(num[0] + num[1], 10);
minute = parseInt(num[2] + num[3], 10);
break;
case numLength === 3:
hour = parseInt(num[0], 10);
minute = parseInt(num[1] + num[2], 10);
break;
case numLength === 2:
case numLength === 1:
hour = parseInt(num[0] + (num[1] || ''), 10);
minute = 0;
break;
// set default time as 12:00 PM when not able to parse
default:
hour = 12;
minute = 0;
}
// Finding AM/PM
pm = stringContainsLetterP || ( !stringContainsLetterA && hour >= 12 && hour < 24 ) ;
// Make sure hour is in 24 hour format
if( pm === true && hour >=0 && hour < 12 ) hour += 12;
if( !pm && hour == 12 ) hour = 0;
// This is the part of the validation
// Keep within range
// if hour is not valid or out of range --> default to 12:00PM
if( hour < 0 || hour > 24){
hour = 12;
minute = 0;
}
//if minute is out of range --> set only minute to 0
if( minute < 0 || minute > 59) minute = 0;
//set Temp date obj to hours and minutes found out above by parsing time string
tempDateObj.setHours(hour,minute);
return tempDateObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment