<script>
// 不足10位补零
function addZero (val){
val = Number(val)
return val < 10 ? '0' + val : val
}
// 时间
let time = '2019-5-30 12:0:0'
// 基于日期 格式化时间字符串
function formatTime(time) {
time = time.replace(/-/g,'/')
time = new Date(time)
let year = time.getFullYear(),
month = addZero(time.getMonth() + 1),
day = addZero(time.getDate()),
hours = addZero(time.getHours()),
minutes = addZero(time.getMinutes()),
seconds = addZero(time.getSeconds())
return year + '年' +
month + '月' +
day + '日 ' +
hours + ':' +
minutes + ':' +
seconds
}
time = formatTime(time)
console.log(time)
// 基于字符串 格式时间
function formatTime(time){
let ary = time.split(' '),
aryLeft = ary[0].split('-'),
aryRight = ary[1].split(':')
ary = aryLeft.concat(aryRight)
let result = ary[0] + '年' +
addZero(ary[1]) + '月' +
addZero(ary[2]) + '日' +
' ' +
addZero(ary[3]) + ':' +
addZero(ary[4]) + ':' +
addZero(ary[5])
return result
}
time = formatTime(time)
console.log(time)
</script>
//万能格式化日期方法
<script>
String.prototype.formatTime = function formatTime(template) {
// 初始模板
typeof template === 'undefined' ? template = "{0}年{1}月{2}日 {3}:{4}:{5}" : null
let matchAry = this.match(/\d+/g)
template = template.replace(/\{(\d+)\}/g,(x, y) => {
let val = matchAry[y] || '00'
val.length < 2 ? val = '0' + val : null
return val
})
return template
}
let time = '2019-5-30 12:0:0'
console.log(time.formatTime("{1}-{2} {3}:{4}"))
</script>
js格式化日期
最新推荐文章于 2024-03-25 17:17:54 发布