Javascript time formatting function

While working on a web application, I found myself with the need for a Javascript function that would format dates to a consistent state. Several different functions exist out on the internet to perform this task, but none were exactly what I was looking for. Most of them did a fairly decent job of taking a time like ’6:45′ and plugging the am or pm onto the end. Some even allowed military time so ’20:30′ would convert to ’8:30 pm’. What I really needed was one that could format a time entered in a normal fashion, but also format if I enter a time like ’0645′ or ’2315′. So, I wrote my own.

There is one support function required. It is a Javascript method that has the same function as VBScript Trim. The way the application is set up, a blank time is valid; so the script allows for a blank field. If a space is entered into the field, this function blanks it out. I found the function TrimString here.

function TrimString(sInString) {
  sInString = sInString.replace( /^s+/g, "" );// strip leading
  return sInString.replace( /s+$/g, "" );// strip trailing
}

And, here is the main function. To use it, add ‘javascript:formattime(this)’ to the onBlur field for an input field.

function formattime(control)
	{
	var minhour = 6;		//This and higher is considered 'am'

	var timevalue = new String(control.value);
	var errvalue = new String("");

	var minutes = new String("");
	var hours = new String("");
	var ampm = new String("");

	if (timevalue == "")
		{
		errvalue = "Blank";
		}

	if (timevalue.indexOf(":")!=-1)
	/*	This is a 'normal' time.  Split it out as necessary.	*/
		{
		var tempArray = timevalue.split(":");
		hours = tempArray[0];
		if (isNaN(hours))
		/*	First split is not a valid number, crash out	*/
			{
			errvalue = "Yes";
			}
		else
			{
			/*	Make sure the number is between 0 and 23	*/
			if ((hours > 23) || (hours < 0))
				{
				errvalue = "Yes";
				}
			else
				{
				if (hours > 12)
					{
					hours = hours - 12;
					ampm = "pm";
					}
				else if (hours == 12)
					{
					ampm = "pm";
					}
				else if (hours == 0)
					{
					ampm = "am";
					hours = 12;
					}
				else
					{
					if (hours < minhour)
						{
						ampm = "pm";
						}
					else
						{
						ampm = "am";
						}
					hours = hours;
					}
				}
			}
		/*	Gen the minutes	*/
		minutes = tempArray[1];
		if (minutes.indexOf("a") > -1)
			{
			ampm = "am";
			minutes = parseInt(minutes);
			}
		else if (minutes.indexOf("p") > -1)
			{
			ampm = "pm";
			minutes = parseInt(minutes);
			}
		else
			{
			minutes = parseInt(minutes);
			}
		/*	Make sure the minutes are in a valid range (00-59)	*/
		if (isNaN(minutes))
			{
			errvalue = "Yes";
			minutes = 0;	//Just to make sure for later
			}
		else
			{
			if ((minutes &lt;0) || (minutes > 59))
				{
				minutes = 0;
				errvalue = "Yes";
				}
			else
				{
				//Minutes is valid
				if (minutes < 10)
					{
					minutes = "0" + String(minutes);
					}
				else
					{
					minutes = minutes;
					}
				}
			}
		}
	else
	/*	Have to work a little harder	*/
		{
		if (isNaN(timevalue))
			{
			errvalue = "Yes";
			}
		else
			{
			if ((timevalue.length == 3) || (timevalue.length ==4))
				{
				//Get the minutes
				minutes = timevalue.substr((timevalue.length -2), 2);
				if ((minutes >= 0) && (minutes < 60))
					{
					//Ignore this
					}
				else
					{
					errvalue = "Yes";
					}

				//Get the hours
				hours = timevalue.substr(0, (timevalue.length - 2));
				if ((hours < 0) || (hours > 23))
					{
					errvalue = "Yes";
					}
				if (hours < 10)
					{
					if (timevalue.substr(0,1)=="0")
						{
						if (hours == 0)
							{
							ampm = "am";
							hours = 12;
							}
						else
							{
							ampm = "am";
							}
						}
					else
						{
						if (hours < minhour)
							{
							ampm = "pm";
							}
						else
							{
							ampm = "am";
							}
						}
					}
				else
					{
					if ((hours == 10) || (hours == 11))
						{
						ampm = "am";
						}
					else if (hours == 12)
						{
						ampm = "pm";
						}
					else
						{
						ampm = "pm";
						hours = hours - 12;
						}
					}
				}
			else
				{
				errvalue = "Yes";
				}
			}
		}
	if (errvalue!="")
	/*	There was an error	*/
		{
		if (TrimString(control.value)!="")
			{
			alert("You appear to have entered an invalid time.  Please correct it.");
			control.select();
			control.focus();
			}
		}
	else
		{
		control.value = (hours * 1) + ":" + minutes + " " + ampm;
		}

	}
This entry was posted in Programming. Bookmark the permalink.

One Response to Javascript time formatting function

  1. Richard Bos says:

    Thanks, saved me some time :)

    Richard.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>