convert time 12 hour format to 24 hour format and vice-versa

javascript, jquery, regex, string, time

Solution

HTML

<input type="text" id="textbox1"/>
<input type="button" id="b1" value="convert 12 hr"/>
<input type="button" id="b2" value="convert 24 hr"/>
<div id="result"></div>

JS

$(document).ready(function () {
    function am_pm_to_hours(time) {
        console.log(time);
        var hours = Number(time.match(/^(\d+)/)[1]);
        var minutes = Number(time.match(/:(\d+)/)[1]);
        var AMPM = time.match(/\s(.*)$/)[1];
        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;
        return (sHours +':'+sMinutes);
    }

    function hours_am_pm(time) {
        var hours = time[0] + time[1];
        var min = time[2] + time[3];
        if (hours < 12) {
            return hours + ':' + min + ' AM';
        } else {
            hours=hours - 12;
            hours=(hours.length < 10) ? '0'+hours:hours;
            return hours+ ':' + min + ' PM';
        }
    }
    $('#b1').click(function(){
         var n = $('#textbox1').val();
         var n1 =n.split('_');
         var time = hours_am_pm(n1[0]+n1[1]);
        $('#result').text(time);
    }); 
    $('#b2').click(function(){
        var n = $('#textbox1').val();
         var n1 =n.split('_');
        var time = am_pm_to_hours(n1[0]+':'+n1[1]+' '+n1[2]);
        $('#result').text(time);
    });

});

Working Demo http://jsfiddle.net/cse_tushar/xEuUR/

updated after Adrian P 's comment

Working Demo http://jsfiddle.net/cse_tushar/xEuUR/4

function hours_am_pm(time) {
    var hours = Number(time.match(/^(\d+)/)[1]);
    var min =  Number(time.match(/:(\d+)/)[1]);
    if (min < 10) min = "0" + min;
    if (hours < 12) {
        return hours + ':' + min + ' AM';
    } else {
        hours=hours - 12;
        hours=(hours < 10) ? '0'+hours:hours;
        return hours+ ':' + min + ' PM';
    }
}

Problem

I want a js script that converts inputted time to 24 hour format or 12 hour format. Example, time is entered as `10_10_am` result should be:- `10:10 AM` (12 hr format) and `10:10` (24 hr format) time is entered as `10_10_pm` result should be:- `10:10 PM` (12 hr format) and `22:10` (24 hr format)

Original source