【发布时间】:2019-07-31 06:00:14
【问题描述】:
我们如何在时间格式的个位数前添加 0。 就像我有时间“0:3:25”(hh:mm:ss)格式转换成“00:03:25”
【问题讨论】:
-
你必须使用像moment.js这样的库或者在javascript中使用switch case
标签: javascript jquery
我们如何在时间格式的个位数前添加 0。 就像我有时间“0:3:25”(hh:mm:ss)格式转换成“00:03:25”
【问题讨论】:
标签: javascript jquery
你不应该过于复杂:
const time = "0:3:25";
const paddedTime = time.split(':').map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
用分号 (:) 分割字符串,生成一个数组(小时、分钟、秒)。 map 这个数组带有一个函数,该函数在数组中的每个项目之前添加一个 0,然后对最后两位数字进行切片(您再次得到一个数组)。然后用分号加入结果数组(你会得到一个字符串)。
或者您可以使用 regex 代替拆分:
const time = "0:3:25";
const paddedTime = time.match(/\d+/g).map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
最后一部分与regex相同(map、slice、join)。
您也可以使用 padStart()(JavaScript 内置函数):
const time = "0:3:25";
const paddedTime = time.split(':').map(e => e.padStart(2, 0)).join(':')
console.log(paddedTime)
padStart() 在 MDN 上:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
【讨论】:
您可以执行以下操作(包括说明):
const time = '0:3:25';
const correctedTime = parseTime(time);
console.log(correctedTime);
function parseTime(time){
return time
.split(':') // Split them into array as chunk of [hour, minute, second]
.map(pad) // Map them with `pad` function below
.join(':'); // Join them back into 'hh:mm:ss'
}
function pad(n){
return parseInt(n) < 10 // If number less than 10
? '0' + n // Add '0' in front
: n; // Else, return the original string.
}
【讨论】:
您可以在“:”上添加拆分现有时间字符串,然后为每个部分添加“0”,然后取最后两个字符。然后只需将这些部分重新组合成一个字符串。
let time = "0:3:25";
function updateTime(){
let newTimePortions = [];
let timePortions = time.split(":");
timePortions.forEach(function(portion,index) {
newTimePortions[index] = ("0" + portion).slice(-2)
})
return newTimePortions.join(':')
}
console.log(updateTime()); // gives 00:03:25
【讨论】:
请尝试以下代码
var dateinfo="0:3:25";
var newdate=dateinfo.split(":");
var hdate=newdate[0];
var mdate=newdate[1];
var sdate=newdate[2];
if(hdate.length == 1 ){
hdate="0"+hdate;
}
if(mdate.length == 1 ){
mdate="0"+mdate;
}
if(sdate.length == 1 ){
sdate="0"+sdate;
}
dateinfo=hdate+":"+mdate+":"+sdate;
这对我有用
【讨论】: