一、通常解决方案
function dataLeftCompleting(value){
return parseInt(value) < 10 ? "0" + value : value;
}
// 测试
var originValue = "2016-8-3",
originDate = new Date(originValue);
var formatValue = originDate.getFullYear()
+ "-" + dataLeftCompleting(originDate.getMonth() + 1)
+ "-" + dataLeftCompleting(originDate.getDate()); // "2016-08-03"
二、可扩充的解决方案
/**
* 可扩充的解决方案
* @param bits 格式化位数
* @param identifier 补全字符
* @param value 值
*/
function dataLeftCompleting(bits, identifier, value){
value = Array(bits + 1).join(identifier) + value;
return value.slice(-bits);
}
// 测试
var originValue = "2016-8-3",
originDate = new Date(originValue);
var formatValue = originDate.getFullYear()
+ "-" + dataLeftCompleting(2, "0", originDate.getMonth() + 1)
+ "-" + dataLeftCompleting(2, "0", originDate.getDate()); // "2016-08-03"
三、ES6提供的方法
epeat()方法:
/**
* 可扩充的解决方案
* @param bits 格式化位数
* @param identifier 补全字符
* @param value 值
*/
function dataLeftCompleting(bits, identifier, value){
value = identifier.repeat(bits) + value;
return value.slice(-bits);
}
更为简单的padStart()方法:
"1".padStart(3, "0"); // 001
https://blog.csdn.net/ligang2585116/article/details/52127095?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task