将时间12小时格式转换为24小时格式,反之亦然

1 javascript regex string time jquery

我想要一个js脚本,将输入的时间转换为24小时格式或12小时格式.

例,

  • 输入的时间10_10_am应为: -

    10:10 AM(12小时格式)和10:10(24小时格式)

  • 输入的时间10_10_pm应为: -

    10:10 PM(12小时格式)和22:10(24小时格式)

Tus*_*har 8

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>
Run Code Online (Sandbox Code Playgroud)

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

});
Run Code Online (Sandbox Code Playgroud)

工作演示http://jsfiddle.net/cse_tushar/xEuUR/

在Adrian P发表评论后更新

工作演示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';
    }
}
Run Code Online (Sandbox Code Playgroud)