vue new Date() 转换为年月日时分秒以及星期几(padStart补零) - 附完整示例
new Date():用当前日期和时间创建新的日期对象
效果
2022年07月12日 星期二 17:19:29
一、new Date()
在vue2中使用new Date() 转换为年月日时分秒以及星期几(padStart补零)
二、使用步骤
1、data中声明定时器以及在methods中的方法
代码如下(示例):
data() {
return {
dateTimer: null,
nowTime: ''
};
},
methods: {
timeFormate (timeStamp) {
let y = new Date(timeStamp).getFullYear().toString()
let M = (new Date(timeStamp).getMonth() + 1).toString().padStart(2, '0')
let d = new Date(timeStamp).getDate().toString().padStart(2, '0')
let h = new Date(timeStamp).getHours().toString().padStart(2, '0')
let m = new Date(timeStamp).getMinutes().toString().padStart(2, '0')
let s = new Date(timeStamp).getSeconds().toString().padStart(2, '0')
let w = new Date(timeStamp).getDay().toString()
switch (w) {
case '1':
w = '一'
break
case '2':
w = '二'
break
case '3':
w = '三'
break
case '4':
w = '四'
break
case '5':
w = '五'
break
case '6':
w = '六'
break
default:
w = '日'
}
this.nowTime = `${y}年${M}月${d}日 星期${w} ${h}:${m}:${s}`
},
nowTimes () {
this.timeFormate(new Date())
this.dateTimer = setInterval(this.nowTimes, 1000)
},
}
2、在mouted中挂载数据以及在beforeDestroy中销毁定时器
代码如下(示例):
mouted () {
this.nowTimes()
},
beforeDestroy () {
if (this.dateTimer) {
clearInterval(this.dateTimer)
}
}
三、完整示例
<template>
<div>
<div>{{ nowTime }}</div>
</div>
</template>
<script>
export default {
data() {
return {
dateTimer: null,
nowTime: ''
};
},
methods: {
timeFormate (timeStamp) {
let y = new Date(timeStamp).getFullYear().toString()
let M = (new Date(timeStamp).getMonth() + 1).toString().padStart(2, '0')
let d = new Date(timeStamp).getDate().toString().padStart(2, '0')
let h = new Date(timeStamp).getHours().toString().padStart(2, '0')
let m = new Date(timeStamp).getMinutes().toString().padStart(2, '0')
let s = new Date(timeStamp).getSeconds().toString().padStart(2, '0')
let w = new Date(timeStamp).getDay().toString()
switch (w) {
case '1':
w = '一'
break
case '2':
w = '二'
break
case '3':
w = '三'
break
case '4':
w = '四'
break
case '5':
w = '五'
break
case '6':
w = '六'
break
default:
w = '日'
}
this.nowTime = `${y}年${M}月${d}日 星期${w} ${h}:${m}:${s}`
},
nowTimes () {
this.timeFormate(new Date())
this.dateTimer = setInterval(this.nowTimes, 1000)
},
},
mounted() {
this.nowTimes()
},
};
</script>