Replace military time to normal time with Javascript

后端 未结 3 1485
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 08:23

With this script

getFormattedTime = function (fourDigitTime){
var hours24 = parseInt(fourDigitTime.substring(0,2));
var hours = ((hours24 + 11) % 12) + 1;
va         


        
3条回答
  •  盖世英雄少女心
    2020-12-10 09:14

    Assuming the only digits displayed in the text are the times you can use:

    var txt = 'Class starts at 0845, please be there by 1630 and sign in by 1645.'
    
    getFormattedTime = function (fourDigitTime) {
        var hours24 = parseInt(fourDigitTime.substring(0, 2),10);
        var hours = ((hours24 + 11) % 12) + 1;
        var amPm = hours24 > 11 ? 'pm' : 'am';
        var minutes = fourDigitTime.substring(2);
    
        return hours + ':' + minutes + amPm;
    };
    /* replace numeric entities*/
    var newTxt = txt.replace(/(\d+)/g, function (match) {
        return getFormattedTime(match)
    })
    $('body').html(newTxt);
    

    DEMO : http://jsfiddle.net/q6HC9/1

    EDIT: Wrapping times in a tag would greatly simplify situation. Wrap all military times in a span with a common class and then use the html() method

    0845
    
    getFormattedTime = function (fourDigitTime) {
        /* make sure add radix*/
        var hours24 = parseInt(fourDigitTime.substring(0, 2),10);
        var hours = ((hours24 + 11) % 12) + 1;
        var amPm = hours24 > 11 ? 'pm' : 'am';
        var minutes = fourDigitTime.substring(2);
    
        return hours + ':' + minutes + amPm;
    };
    /* find all spans and replace their content*/
    $('span.mil_time').html(function( i, oldHtml){
       return getFormattedTime(oldHtml);
    })
    

提交回复
热议问题