3

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)

4

2 回答 2

13

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

});

工作演示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';
    }
}
于 2013-07-16T11:04:31.313 回答
0

我不确定是否已经存在任何特定功能,但这很容易编写。

考虑到您的输入始终是##_##_pm,或者##_##_am您可以在每个字符串上拆分此字符串_并将第一个值作为hours, secondasminutes并比较第三个和

如果是 pm 添加12 hours到 hours 变量中24 hr format。您需要一个带有 2 个参数(格式和字符串)的函数,它看起来像这样:

function timeFormat(format, str){
    var timeParts=str.split("_");
    if(format==12){
       return timeParts[0] + ":" + timeParts[1] + " " + timeParts[2];
    }else if(format == 24){
       var hours = timeParts[0];
       if(timeParts[2] == "pm")
           hours += 12;
       return hours + ":" + timeParts[1]
    }
}
于 2013-07-16T10:55:44.513 回答