gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:24:48 25 4
gpt4 key购买 nike

我有一个输入字段:

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

最佳答案

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

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/

关于javascript - 将数字格式化为时间,如 hh :mm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13044520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com