我收到的字符串可能是以下列表中的任何一个:
7
5:45
11:05
23:5
14:3
而且我希望总是以这样的方式结束:
07:00
05:45
11:05
23:50
14:30
etc
我怎样才能用 Javascript 编写一个很好的函数接受它并给我正确的输出?请记住,单个小时值不会有冒号,例如列表开头的 7。
我尝试使用 PadZero 函数:
Number.prototype.padZero= function(len){
var s= String(this), c= '0';
len= len || 2;
while(s.length < len) s= c + s;
return s;
}
与
var formattedY = this.x.padZero().toString().replace('.',':');
附注我的实际值返回为 11.5 或 23.45,但我想要 11:50 和 23:45
最佳答案
这个函数应该可以解决你的问题。
function format_time(invalid_time_string) {
var corrected_time = invalid_time_string;
if (invalid_time_string.length === 1) {
invalid_time_string = "0" + invalid_time_string + ":00";
corrected_time = invalid_time_string;
} else {
if (invalid_time_string.length < 5) {
var hours_minutes = invalid_time_string.split(":");
if (hours_minutes[0].length != 2) {
var corrected_hours = "0" + hours_minutes[0];
} else {
var corrected_hours = hours_minutes[0];
}
if (hours_minutes[1].length != 2) {
var corrected_minutes = hours_minutes[1] + "0";
} else {
var corrected_minutes = hours_minutes[1];
}
corrected_time = corrected_hours + ":" + corrected_minutes;
}
}
return corrected_time;
}
var correct_time = format_time("5:45");
console.log(correct_time);
关于Javascript将不同的字符串格式化成标准的区间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388595/