# [RESOLVED]convert 12-hour hh:mm AM/PM to 24-hour hh:mm

suppose i have time in 12 hrs format like 02:05 PM which i want to programmatically convert to 24 hrs format like 13:05. looking for function where i will send 12 hrs format time and function will return 24 hrs format time……any help would be appreciated.
thanks

var time='02:05 PM';

var hours = Number(time.match(/^(d+)/)[1]);
var minutes = Number(time.match(/:(d+)/)[1]);
var AMPM = time.match(/s(.*)\$/)[1].toLowerCase();

if (AMPM == "pm" && hours < 12) hours = hours + 12;
if (AMPM == "am" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;

You can use the below code to convert 12hour format to 24 hour format in javascript

function ConvertTime()
{
var inputval = document.getElementById('txttime').value;

var tokens = /([10]?d):([0-5]d) ([ap]m)/i.exec(inputval);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
var convertedval = tokens[1] + ':' + tokens[2];

}

Complete Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<title></title>
<script>
function ConvertTime() {
//Get the textbox value here
var inputval = document.getElementById('<%=txttime.ClientID%>').value;
var tokens = /([10]?d):([0-5]d) ([ap]m)/i.exec(inputval);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
var convertedval = tokens[1] + ':' + tokens[2];

}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txttime" runat="server" Text="02:05 PM"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ConvertTime();" />
</form>
</body>
</html>

Source URL

The easiest way to handle this with any consistency would be to use a time-related library like
Moment.js, which can easily handle formatting and parsing dates. I would highly recommend it as I have used it extensively in the past and it works like a charm.

If you wanted to handle this on your own however, you could add a bit of logic to perform your conversion :

var dt = "2:05 PM";

// A function to convert your 12-hour clock in to a 24-hour one
function ConvertTime(t){
// Get your time (using a hard-coded year for parsing purposes)
var time = new Date("0001-01-01 " + t);