JavaScript - How to validate time in 12 hour format in javascript

Asked By Manu on 05-Aug-11 11:11 AM
Hi,

I need to validate a time in 12 hour format in javascript, how can i do this?

Thanks
Web Star replied to Manu on 05-Aug-11 11:20 AM

In this example, the date fields will only accept input that matches the pattern 'dd/mm/yyyy' (this could just as easily be changed to 'yyyy-mm-dd' or 'mm/dd/yyyy'). The time field will allow input starting with 'hh:mm' following by an optional 'am' or 'pm'. The fields can also be empty.

Event Details (dd/mm/yyyy) (eg. 17:17 or 5:17pm) (eg. 5/8/2026)

The code behind the form is as follows:

function checkForm(form) { // regular expression to match required date format re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; if(form.startdate.value != '' && !form.startdate.value.match(re)) { alert("Invalid date format: " + form.startdate.value); form.startdate.focus(); return false; } if(form.enddate.value != '' && !form.enddate.value.match(re)) { alert("Invalid date format: " + form.enddate.value); form.enddate.focus(); return false; } // regular expression to match required time format re = /^\d{1,2}:\d{2}([ap]m)?$/; if(form.starttime.value != '' && !form.starttime.value.match(re)) { alert("Invalid time format: " + form.starttime.value); form.starttime.focus(); return false; } alert("All input fields have been validated!"); return true; }

For each field in the form (first the dates, then the time field), a check is made as to whether the input is blank. If not, the input is compared to the regular expression. The expressions use a pre-defined class \d which represents any numeric character (0-9).

Web Star replied to Manu on 05-Aug-11 11:26 AM

function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour <= 12 && ampm == null) {
if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
   }
}
if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute<0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return false;
}
//  End -->
</script>
</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<center>
<form name=timeform onSubmit="return IsValidTime(document.timeform.time.value);">
Time (HH:MM:SS AM/PM format)  <input type=text name=time><br>
<input type="submit" value="Submit">
</form>
</center>

<p><center>
<font face="arial, helvetica" size="-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com%22%20originalattribute=%22href%22%20originalpath=%22/ JavaScript Source</a></font>
</center><p>

TSN ... replied to Manu on 05-Aug-11 12:16 PM
hi..

try using Regex..

Check if time is in 24h format hh:mm For example these values are valid: 01:00 (leading zero is mandatory), 05:01, 13:00, 23:59. For example these values are not valid: 24:00, 1:30, 05:60, 12|34 etc.

Regex: ([0-1]\d|2[0-3]):([0-5]\d)

Ravi S replied to Manu on 05-Aug-11 12:22 PM
HI

try this

protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("With Seconds" + "<br />");
        Response.Write("12 Hour Date Format : " + DateTime.Now.ToString("hh:mm:ss tt") + "<br />");
        Response.Write("24 Hour Date Format : " + DateTime.Now.ToString("HH:mm:ss tt") + "<br />");
        Response.Write("Without Seconds" + "<br />");
        Response.Write("12 Hour Date Format : " + DateTime.Now.ToString("hh:mm tt") + "<br />");
        Response.Write("24 Hour Date Format : " + DateTime.Now.ToString("HH:mm tt") + "<br />");
    }
(or)
<script type="text/javascript">
<!--
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
   {
   a_p = "AM";
   }
else
   {
   a_p = "PM";
   }
if (curr_hour == 0)
   {
   curr_hour = 12;
   }
if (curr_hour > 12)
   {
   curr_hour = curr_hour - 12;
   }

var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min + " " + a_p);
//-->
</script>
refer the links also
http://www.mkyong.com/regular-expressions/how-to-validate-time-in-12-hours-format-with-regular-expression/
http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php3
Ravi S replied to Manu on 05-Aug-11 12:24 PM
HI

<html>
<head>
<script type="text/javascript" language="JavaScript">
<!-- Copyright 2002 Bontrager Connection, LLC
function getCalendarDate()
{
   var months = new Array(13);
   months[0]  = "January";
   months[1]  = "February";
   months[2]  = "March";
   months[3]  = "April";
   months[4]  = "May";
   months[5]  = "June";
   months[6]  = "July";
   months[7]  = "August";
   months[8]  = "September";
   months[9]  = "October";
   months[10] = "November";
   months[11] = "December";
   var now         = new Date();
   var monthnumber = now.getMonth();
   var monthname   = months[monthnumber];
   var monthday    = now.getDate();
   var year        = now.getYear();
   if(year < 2000) { year = year + 1900; }
   var dateString = monthname +
                    ' ' +
                    monthday +
                    ', ' +
                    year;
   return dateString;
} // function getCalendarDate()
function getClockTime()
{
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour +
                    ':' +
                    minute +
                    ':' +
                    second +
                    " " +
                    ap;
   return timeString;
} // function getClockTime()
//-->
</script>

</head>
<body>
<script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script>
</body>
</html>
Manu replied to Manu on 08-Aug-11 02:15 AM
Got the solution-

/^((0?[1-9])|(1[0-2]))(((:|\s)[0-5]+[0-9]+))$/