Skip to content

Instantly share code, notes, and snippets.

@yxkelan
Created November 3, 2012 06:05
Show Gist options
  • Save yxkelan/4006247 to your computer and use it in GitHub Desktop.
Save yxkelan/4006247 to your computer and use it in GitHub Desktop.
Check time format and transfer 12-hour to 24-hour format
/* The original source: http://www.the-art-of-web.com/javascript/validate-date/ */
//obj is JQuery object
// return : true -- time invalid, false -- time valid
function checkTime(obj){
var errorFlag = false;
re = /^(\d{1,2}):(\d{2})(:00)?([apAP][mM])?$/;
if (regs = obj.val().match(re)){
if(regs[4]){
//12-hour time format with am/pm
if (regs[1]<1 || regs[1]>12){
errorFlag = true;
}
if (regs[4].toLowerCase() == 'am' && regs[1] == 12 ){ //Need convert 12-hour to 24-hour
regs[1]= '00';
}else if(regs[4].toLowerCase() =='pm' && regs[1]<12){
regs[1] = parseInt(regs[1])+12;
}
obj.val([regs[1],':',regs[2]].join(''));
}else{
//24-hour time format
if(regs[1]>23){
errorFlag = true;
}
}
if( regs[2]>59){
errorFlag = true;
}
}else{
errorFlag = true;
}
return errorFlag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment