JavaScript: Convert time format to 24 Hour with leading zeros

hankknight
hankknight used Ask the Experts™
on
Using JavaScript, I want to convert an am/pm time to 24 hour time with leading zeros.

1:00 am
Should become
01:00

1:00 pm
Should become
13:00

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Is  your time value initially a string or a javascript date object?

Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

Author

Commented:
The idea in the link does not work for me:
theDate.format("H:MM")

It does not work because my time value is a string, not a date object.

My code below demonstrates what I need, although my function is incomplete.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>

</head>
<body>

<script type="text/javascript">
/*<![CDATA[*/

alert(time24('1:11 am') + '\nShould be 01:11');
alert(time24('2:22 pm') + '\nShould be 14:22');

function time24(str) {
 return str;
}

/*]]>*/
</script>

</body>
</html>

Open in new window

Commented:
Something like this than? It is a bit hacked and does not check the input, but it provides the output;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>

</head>
<body>

<script type="text/javascript">
/*<![CDATA[*/

alert(time24('1:11 am') + '\nShould be 01:11');
alert(time24('2:22 pm') + '\nShould be 14:22');

function time24(str) {
 var hour;
 var minute;

 hour = str.substring(0, str.indexOf(':'));
 minute = str.substring(str.indexOf(':') + 1, 5);
 alert(hour);
 alert(minute);
 if (str.indexOf('pm') > 0)
 {
   hour = parseInt(hour) + 12;
 }
 
 if (hour < 12)
 {
  str = "0";
 } 
 else
 {
  str = "";
 }

 str = str + hour + ":" + minute;
 return str;
}

/*]]>*/
</script>

</body>
</html>

Open in new window

Michel PlungjanIT Expert
Top Expert 2009

Commented:
Here is another take using the more appropriate split which handles 12:13am = 00:13 for example


function mil(str) {
  var t = str.split(':')
  var hh = parseInt(t[0],10);
  var isAM = str.toLowerCase().indexOf('am')!=-1;
  hh -= (isAM && hh==12)?12:0;
  hh += (isAM)?0:12;
  if (hh<10) hh="0"+hh;  
  return ""+hh+':'+t[1];
}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial