Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created November 9, 2011 22:08
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 justinobney/1353261 to your computer and use it in GitHub Desktop.
Save justinobney/1353261 to your computer and use it in GitHub Desktop.
This validates and returns various different time values in javascript
//Author: Justin Obney
//This should return an array with validity and other info
// pass = [true, date object, regex match array, date object toString (for testing) ]
// fail = [false, "error message"]
// should return valid date objects the following:
// 8:00am -standard w/ no preceding "0"
// 09:00am -standard w/ preceding "0"
// 7:13p -matches p to "PM"
// 14:35 -accepts 24 hour time
// 5a -accepts hour + a for 5:00 AM
// 10am -same with "am"
// 12 p -same with " p"
// 5 pm -same with " pm"
function checkTime(input, optional_date) // if optional_date is omitted, returned date will use current date
{
var errorMsg = "",
hour,
min,
timeofday;
// regular expression to match required time format
re = /^(\d{1,2})(:\d{2})?(\s?[ap]m?)?$/;
if(input != '') {
if(regs = input.match(re)) {
if(parseFloat(regs[1]) > 0 && parseFloat(regs[1]) < 13) {
// 12-hour time format
if(regs[3]){
//has am/pm
hour = parseFloat(regs[1]);
if (regs[3].toUpperCase().indexOf('P') != -1){
//its pm --> add 12
hour += 12;
}
} else {
//no am/pm
//assume am ???? throw error ????
errorMsg = "Invalid value for AM/PM:";
}
} else if(regs[1] < 24) {
// 24-hour time format
// assume pm
hour = parseInt(regs[1]);
} else {
errorMsg = "Invalid value for hours: " + regs[1];
}
if(!errorMsg && regs[2]) {
// has minutes field
min = parseInt(regs[2].replace(':',''));
} else {
// has no minutes field.. assume :00
min = 0;
}
} else {
errorMsg = "Invalid time format: " + input;
}
}
if(errorMsg != "") {
return [false, errorMsg];
}
var today = (optional_date || new Date()) ,
year = today.getYear(),
month = today.getMonth(),
day = today.getDate();
var d = new Date(year + 1900, month, day, hour, min, 0, 0);
function getStandardTime(time) {
var hour, minute, tod = 'AM';
if (time.getHours() > 12) {
hour = time.getHours() - 12;
tod = 'PM';
} else {
hour = time.getHours();
}
minute = time.getMinutes();
var padHour = (hour < 10) ? '0' + hour : hour;
var padMinute = (minute < 10) ? '0' + minute : minute;
return padHour + ':' + padMinute + ' ' + tod;
}
return [ true, d, regs, d.toString(), getStandardTime(d) ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment