将数字格式化为时间,如hh:mm

时间:2012-10-24 07:20:24

标签: javascript jquery formatting format

我有一个输入字段:

<input type="text" name="time" class="time" value="3" />

我需要这个值就像03:00

我需要的更多例子:

1 = 01:00
12 = 12:00
12:2 = 12:20
2:2 = 02:20
02:2 = 02:20
340 = 340:00
340:1 = 340:10

你知道其余的。我怎样才能在jquery / javascript中解决这个问题?

这是我在jQuery中尝试的内容:

$('input').blur(timeFormat);

function timeFormat(e){
    skjema.find('input.tid').each(function(){
        if($(this).val().length != 0){
            var tid = $(this).val().toString();

            if(tid.length == 1){

                $(this).val(String("0" + tid));

            }
            if(tid.indexOf(':') == -1){
                $(this).val(tid.toString() + ':00');
            }
        }
    });
}

这就是我现在所做的,它完成了这项工作,但它有点笨重:)

function timeFormat(e){
    skjema.find('input.tid').each(function(){
        if($(this).val().length != 0){
            var tid = $(this).val().toString();
            tid = (tid.length == 1) ? '0' + tid : tid;
            tid = (tid.indexOf(':') == -1) ? tid + ':00' : tid;
            if(tid.indexOf(':') != -1){
                var arr = tid.split(':');
                var before = arr[0].toString();
                var after = arr[1].toString();
                before = (before.length == 0) ? '00' : before;
                before = (before.length == 1) ? '0' + before : before;
                after = (after.length == 0) ? '00' : after;
                after = (after.length == 1) ? after + '0' : after;
                console.log('before: ' + before + ' After: ' + after);
                tid = before + ':' + after;
            }
        }
        $(this).val(tid);
    });
}

7 个答案:

答案 0 :(得分:5)

你可以用一些简单的正则表达式来做到这一点:

function time( str ) {
    if ( !/:/.test( str ) ) { str += ':00'; }
    return str.replace(/^\d{1}:/, '0$&').replace(/:\d{1}$/, '$&0' );
}

如果您想确保只接受预期的格式,请在函数顶部添加以下行:

if ( /[^:\d]/.test( str ) ) { return false; }

演示: http://jsfiddle.net/elclanrs/MzgMz/

答案 1 :(得分:2)

你可以使用datejs库尝试这样的事情: -

 var dateString = "12";
 var date = new Date.parseExact(dateString, "hh:mm");

答案 2 :(得分:1)

检查此DEMO

$('input').blur(timeFormat);

function timeFormat(e){ 
    $("div").find('input').each(function(){
        if($(this).val().length != 0){
            var tid = $(this).val().toString();

            if(tid.length == 1){

                $(this).val(String("0" + tid));

            }
            if(tid.indexOf(':') == -1){
                $(this).val(tid.toString() + ':00');
            }
            if(tid.indexOf(':') == 2){
                $(this).val(tid.toString() + '0');
            }
        }
    });
}​

答案 3 :(得分:1)

<title>Insert Colon in the Time Format</title>

<script type="text/javascript">
function formatTime(objFormField){
intFieldLength = objFormField.value.length;

if(intFieldLength==2 || intFieldLength == 2){
     objFormField.value = objFormField.value + ":";
     return false;
    } 
}
</script>

Enter time <input type="text" maxlength="5" minlength="5" onKeyPress="formatTime(this)"/>

答案 4 :(得分:0)

伪:

  1. val←来自字段($('.time').val()
  2. 的值
  3. colonPos.
  4. val的位置
  5. 如果colonPos等于-1,resultpadZero(val) + ':00'
  6. 其他,resultpadZero(val[:colonPos]) + ':' + padZero(val[colonPos + 1:])

答案 5 :(得分:0)

function prettyTime(t){
  // will output a time providing leading zeros and minute field
  // (doesn't need jQuery)

  x=t.split(":");

  for (var i=0; i<2; i++)
    x[i] = (x[i]) ? Array(3-x[i].length).join('0') + x[i] : '00';

  return x.join(":");

}

// --

$('input').blur(timeFormat);

function timeFormat(e){
    skjema.find('input.tid').each(function(){

        $(this).val(function(i, v) { return prettyTime(v); })

    });
}

答案 6 :(得分:-2)

也许你可以试试this插件..为我工作

使用示例:

$("#tbPlain").timefield();
$("#tb12Hour").timefield({ 'hourFormat': '12'});
$("#tb24Hour").timefield({ 'hourFormat': '24'});
$("#tbWithInvalidHandler").timefield({ 
        'hourFormat': '24',
        'onError'   : function(){
                alert(this.value+' is not a valid time!');
                this.style.backgroundColor='red';
            }
        });
$("#tbOnOff").timefield();
$("#btnTurnOff").click(function(){
                $("#tbOnOff").timefield('turnOffTimeField');
            });

直播示例:

https://jsfiddle.net/sajjansarkar/bst3cw2g/