Jump to content

Converting 12 Hours Format to 24 Hrs Format


suresh64633

Recommended Posts

<html>
<head>
<script type="text/javascript">

function convert12to24(timeStr)
{
    var meridian = timeStr.substr(timeStr.length-2).toLowerCase();;
    var hours =  timeStr.substr(0, timeStr.indexOf(':'));
    var minutes = timeStr.substring(timeStr.indexOf(':')+1, timeStr.indexOf(' '));
    if (meridian=='pm')
    {
        if (hours!=12)
        {
            hours=hours*1+12;
        }
        else
        {
            hours = (minutes!='00') ? '0' : '24' ;
        }
    }

    return hours+':'+minutes;
}

//This function only for testing
function changeTimeFormat()
{
    var input = document.getElementById('input').value
    var output = convert12to24(input);
    document.getElementById('output').value = output;
}

</script>
</head>

<body>


Input 12 hr format: <input type="text" name="input" value="10:30 PM"><br />
Output 24 hr format: <input type="text" name="output" value="" readonly>
<button onclick="changeTimeFormat();">Change</button>
</form>
</body>
</html>

Improved the function.

 

- 00:00 should be used instead of 24:00

- added functionality to ensure hours is always two digits.

 

function convert12to24(timeStr)
{
    var meridian = timeStr.substr(timeStr.length-2).toLowerCase();
    var hours    = timeStr.substring(0, timeStr.indexOf(':'));
    var minutes  = timeStr.substring(timeStr.indexOf(':')+1, timeStr.indexOf(' '));
    if (meridian=='pm')
    {
        hours = (hours=='12') ? '00' : parseInt(hours)+12 ;
    }
    else if(hours.length<2)
    {
        hours = '0' + hours;
    }
    return hours+':'+minutes;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.