我正在尝试创建一个使用数字并使用date-fns版本1.30.1或纯JavaScript返回时间戳记(HH:mm)的函数。
我想要实现的是在输入时间时为用户提供帮助。当用户离开输入字段时,我正在使用Vue.js更新该字段。因此,如果用户键入21然后离开,则该字段理想情况下将更新为21:00。
一些示例是:
21 = 21:00
1 = 01:00
24 = 00:00
2115 = 21:15
像815这样的数字不必返回08:15。像7889这样的数字应返回错误。
我试过使用正则表达式:
time = time
.replace(/^([1-9])$/, '0$1')
.replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
.replace(/^24/, '00:00')
我也尝试在date-fns中使用parse方法,但似乎无法解决这个问题。
基于<100
(仅小时)和>=100
(100 *小时+分钟)的转换,加上一些24
和单位数的数字(小时和分钟)的换算:
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
console.log(num2time(8));
console.log(num2time(801));
console.log(num2time(24));
console.log(num2time(2401));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
24
正确处理 或只用一位数表示分钟:
例如,您可以进行非常机械的转换
function num2time(num){
if(num<10)
t="0"+num+":00";
else if(num<100)
t=num+":00";
else {
if(num<1000)
t="0"+Math.floor(num/100);
else if(num<2400)
t=Math.floor(num/100)
else
t="00";
t+=":"+(num%100);
}
return t;
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
if(h<0 || h>24) throw "Hour must be between 0 and 24"
if(m<0 || m>59) throw "Minute must be between 0 and 59"
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
var numstr=prompt("Enter time code");
while(true) {
try {
console.log(num2time(numstr));
break;
} catch(ex) {
numstr=prompt("Enter time code, "+numstr+" is not valid\n"+ex);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句