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>

Link to comment
Share on other sites

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;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.