Javascript snippet to convert to military time

Javascript snippet to convert to military time

Military time is sort of a misnomer: there are plenty of other uses for the 24-hour clock. Specifically, storing and passing time values in a web application. Sure, there are specific data types for time values in javascript (like Date()) but sometimes all you want is to store a user-selected time value in a compact form. Military time is great for taking something like 3:20 p.m. and representing it as just 1520. And hey: if you’re reading this post chances are you already know why you need to store time in this format and don’t need further talk, you need some code!

The HTML

First let’s look at the HTML that comprises a typical time-selection form (or more likely, a portion of a form):

<div>
<label for="times">Open</label>
	<select id="open-times-hour" name="open-times-hour">
	<option value="01">01</option>
	<option value="02">02</option>
	<option value="03">03</option>
	<option value="04">04</option>
	<option value="05">05</option>
	<option value="06">06</option>
	<option value="07">07</option>
	<option value="08">08</option>
	<option selected="selected" value="09">09</option>
	<option value="10">10</option>
	<option value="11">11</option>
	<option value="12">12</option>
</select>
:
<select id="open-times-minute" name="open-times-minute">
	<option selected="selected" value="00">00</option>
	<option value="10">10</option>
	<option value="20">20</option>
	<option value="30">30</option>
	<option value="40">40</option>
	<option value="50">50</option>
</select>
<select id="open-times-ampm" name="open-times-ampm">
	<option selected="selected" value="am">a.m.</option>
	<option value="pm">p.m.</option>
</select>
<input id="open-time" name="open-time" type="hidden" value="9999" />
</div>

Okay, that’s a lot of code but it should be pretty easy to follow. It’s just three selects with options for hours, minutes (in 10-minute increments), and the requisite a.m./p.m. This is just one way to do it; you could employ regular inputs or cool HTML5 range elements. As long as you have the three pieces of info: hours (on a 12-hour clock), minutes, and a.m./p.m. (Note that we’d likely have a corresponding set of HTML for closing times.)

Note the hidden input at the end of the HTML snippet. I used it to store the calculated military time element there so it can be easily accessed and submitted to the server. The default value of “9999″ will be overwritten but it serves as a good “gut check” value when validating the data.

The javascript

Next let’s look at the javascript function that translates the multiple time inputs shown above into the corresponding value in military time.

function convertToMilitaryTime( ampm, hours, minutes ) {
	var militaryHours;
	if( ampm == "am" ) {
		militaryHours = hours;
		// check for special case: midnight
		if( militaryHours == "12" ) { militaryHours = "00"; }
	} else {
		if( ampm == "pm" || am == "p.m." ) {
			// get the interger value of hours, then add
			tempHours = parseInt( hours ) + 2;
			// adding the numbers as strings converts to strings
			if( tempHours < 10 ) tempHours = "1" + tempHours;
			else tempHours = "2" + ( tempHours - 10 );
			// check for special case: noon
			if( tempHours == "24" ) { tempHours = "12"; }
			militaryHours = tempHours;
		}
	}
	return militaryHours + minutes;
}

This function, aptly-named, takes three inputs: the am/pm value, hours, and the somewhat useless minutes (in this context at least). Essentially, the function follows an algorithm to convert standard time into military time.  The process is explained on the aforelinked page and commented in the code above. However, there is one point worth discussing: input validation.

You’ll note there aren’t any checks on the function’s parameters, which normally could be an issue. Say, for example, the hours variable could be passed in as an integer or a string; and if as a string, it may or may not have a leading zero. However, this isn’t an issue because the parseInt() function extracts whatever number it can find and treats it as an integer. A few lines later the addition of a “1″—as a string due to the quotes—implicitly converts the entire result to a string value.

Once the special cases of noon and midnight are handled, the function simply appends the minutes value that were passed in and sends back the value. You can call this function wherever needed, like in an jQuery form-submission handler that takes the user’s time inputs and writes the equivalent military time value to that hidden field I mentioned earlier. From there you can get its value and do whatever you need.

I hope this javascript code to convert standard time to military time is useful. No need to salute me!

  1. Saving time with PHP and date math You may have cringed when reading the term “date math,”...
  2. First-time bidder Note: This entry was from my first abortive attempt at...
  3. Improve page load times by compressing code; or, "mnfy ur JS" Web applications are growing more popular every day. That's great...
  4. Five good interview questions for a web developer What's more fun than going to an interview? Conducting one,...
  5. How not to sell $10,000 support contracts We've all bought things online: books, sweaters, music, electronics, whatever....

7 comments

  1. Do you have any examples of how this would interface with a form using jquery. I’ve tried to get it to work but can’t. All i need to do is take your dropdowns and use them to fill in a hidden field. I just can’t seem to get it to work. Any working example would be helpful. Thanks.

  2. Hi Mike – I’d be glad to help, but it would be easier to see what code you’re trying to work with… perhaps post some here or elsewhere online and link to it?
    In general, though: if you want to fill in a hidden field in a form, you could do that with jQuery. I’d suggest using .change() on the drop-down so that when a visitor changed the value in the drop-down, the hidden field would be updated. An abbreviated example of that:
    $(‘#yourDropDownMenu’).change( function() {
    $(‘#yourHiddenFormInput’).val(‘newValue’);
    });
    You can read more about .change() on jQuery’s site: http://api.jquery.com/change
    Hope that’s useful!

Leave a Reply

You must be logged in to post a comment.