let oDate = new Date();
let y=oDate.getFullYear(); //获取当前年份
let M=oDate.getMonth()+1;//获取当前月份,由于获取的是0~11,所以还应该再+1
let day=oDate.getDate();//获取当前日份
let h=oDate.getHours();//获取当前小时
let m=oDate.getMinutes();//获取当前分钟
let s=oDate.getSeconds();//获取当前秒数
let week=oDate.getDay();//获取今天是星期几,由于获取是的从0~6,如果想展示星期几,需要进一步进行数据处理
以下是利用vue做的时间显示例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>{{time.y}}年{{time.M}}月{{time.day}}日 {{time.h}}:{{time.m}}:{{time.s}} {{time.week}}</p>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
time:{
y:2022,//年
M:02,//月
day:17,//日
h:14,//时
m:08,//分
s:00,//秒
week:'星期四'
}
},
methods: {
clock:function(){
let oDate = new Date();
this.time={
y:oDate.getFullYear(),
M:oDate.getMonth()+1,
day:oDate.getDate(),
h:oDate.getHours(),
m:oDate.getMinutes(),
s:oDate.getSeconds(),
week:oDate.getDay(),
}
//月数据处理,个位数时补0
if(parseInt(this.time.M)<10){
this.time.M='0'+parseInt(this.time.M)
}
//日数据处理,个位数时补0
if(parseInt(this.time.day)<10){
this.time.day='0'+parseInt(this.time.day)
}
//时数据处理,个位数时补0
if(parseInt(this.time.h)<10){
this.time.h='0'+parseInt(this.time.h)
}
//分数据处理,个位数时补0
if(parseInt(this.time.m)<10){
this.time.m='0'+parseInt(this.time.m)
}
//秒数据处理,个位数时补0
if(parseInt(this.time.s)<10){
this.time.s='0'+parseInt(this.time.s)
}
//星期处理,展示星期几
let week = parseInt(this.time.week)
switch (week) {
case 1:this.time.week='星期一' ;break;
case 2:this.time.week='星期二' ;break;
case 3:this.time.week='星期三' ;break;
case 4:this.time.week='星期四' ;break;
case 5:this.time.week='星期五' ;break;
case 6:this.time.week='星期六' ;break;
case 7:this.time.week='星期日' ;break;
}
}
},
beforeCreate:function(){
console.log('创建前');
},
created:function(){
console.log('创建后');
},
beforeMount:function(){
console.log('挂载前');
},
mounted:function(){
console.log('挂载后');
setInterval(this.clock, 1000);//每隔一秒执行一次
this.clock();//页面加载时候执行一次
},
beforeUpdate:function(){
console.log('数据更新前');
},
updated:function(){
console.log('数据更新后');
},
beforeDestroy:function(){
console.log('销毁前');
},
destroyed:function(){
console.log('销毁后');
},
})
</script>