2 回答
TA贡献1804条经验 获得超8个赞
转换基于<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);
}
}
TA贡献1887条经验 获得超5个赞
DateFns 实现
恕我直言,致力于添加和删除分钟和小时是管理此转换的更简洁的方法:
function formattedTime(val) {
let helperDate;
if(val.length <= 2) {
if(val > 24)return 'error';
helperDate = dateFns.addHours(new Date(0), val-1);
return dateFns.format(helperDate, 'HH:mm');
}
if(val.length > 2) {
let hhmm = val.match(/.{1,2}/g);
if(hhmm[0] > 24 || hhmm[1] > 60) return 'error';
helperDate = dateFns.addHours(new Date(0), hhmm[0]-1);
helperDate = dateFns.addMinutes(helperDate, hhmm[1]);
return dateFns.format(helperDate, 'HH:mm');
}
}
const myArr = [21, 1, 24, 2115, 815];
myArr.forEach(
val => console.log(formattedTime(val.toString()))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
添加回答
举报