使用方式
输出:
formatTime方法:
function formatTime(countTime = 0, timeStr = "hh:mm:ss") {
let timeSet = {
"h": function (count) {
return parseInt(count / 3600);
},
"m": function (count) {
return parseInt(count % 3600 / 60);
},
"s": function (count) {
return parseInt(count % 60);
}
};
let start = 0;
let queryCharacter = '';
for (let i = 0; i < timeStr.length + 1; i++) {
let character = timeStr[i]; //当前字符
if (character !== queryCharacter) { //当前字符不等于查询字符
if (queryCharacter) { //替换查询字符为时间
let end = i;
let resultStr = String(timeSet[queryCharacter](countTime));
while (resultStr.length < end - start) {
resultStr = '0' + resultStr;
}
timeStr = timeStr.slice(0, start) + resultStr + timeStr.slice(end);
i = start + resultStr.length;
queryCharacter = '';
}
if (character && timeSet[character]) { //更新查询字符和开始角标
queryCharacter = character;
start = i;
}
}
}
return timeStr;
}
代码片段:https://developers.weixin.qq.com/s/Dnfj4Vm97Cls
产品要求低于一小时只显示分和秒,低于一分钟只显示秒,
所有又对这个函数做了一下调整,如果需要最高位为0不显示需要多传入一个参数,
输入:
输出:
代码片段:https://developers.weixin.qq.com/s/wEteGYml7bll
formatTime方法
function formatTime(countTime = 0, timeStr = "hh:mm:ss", removeFirst = false) {
let timeSet = {
"h": function (count) {
return parseInt(count / 3600);
},
"m": function (count) {
return parseInt(count % 3600 / 60);
},
"s": function (count) {
return parseInt(count % 60);
}
};
let start = 0;
let queryCharacter = '';
for (let i = 0; i < timeStr.length + 1; i++) {
let character = timeStr[i]; //当前字符
if (character !== queryCharacter) { //当前字符不等于查询字符
if (queryCharacter) { //替换查询字符为时间
let end = i;
let result = timeSet[queryCharacter](countTime);
let resultStr = '';
if (!removeFirst || result > 0 || start !== 0) {
resultStr = String(result);
while (resultStr.length < end - start) {
resultStr = '0' + resultStr;
}
}
timeStr = timeStr.slice(0, start) + resultStr + timeStr.slice(end);
i = start + resultStr.length;
queryCharacter = '';
}
if (character && timeSet[character]) { //更新查询字符和开始角标
queryCharacter = character;
start = i;
} else {
if (removeFirst && i === 0) {
timeStr = timeStr.slice(1);
i = -1;
}
}
}
}
return timeStr;
}
3天23时20分10秒