Moment.js
安装
npm install moment --save
main.js 引用:
import moment from 'moment';
import 'moment/locale/zh-cn'; // 获取中国标准时间,避免出现utc时间
Vue.prototype.moment = moment
获取当前时间
<template>
<div class="home">
<!-- header -->
<div class="header">
<h2>政府大屏</h2>
<div>{{nowtime | updatetime}}</div>
</div>
</div>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'; // 获取中国标准时间,避免出现utc时间
export default {
name: "Home",
data() {
return {
nowtime: new Date()
};
},
filters: {
updatetime: function(value) {
return moment(value).format('YYYY年MM月DD日h点mm分ss秒');
}
},
mounted() {
//生命周期模板挂载之后
let _this = this;
this.timer = setInterval(() => {
_this.nowtime = new Date();
}, 1000);
},
beforeDestroy() {
//生命周期实例销毁之前
if (this.timer) {
clearInterval(this.timer);
}
}
};
</script>
<style lang="less" scoped>
.home {
width: 100%;
height: 100vh;
font-size: 12px;
background: wheat;
.header {
width: 100%;
height: 100px;
line-height: 30px;
position: relative;
h2 {
font-weight: 550;
text-align: center;
color: white;
}
div {
text-align: right;
font-size: 8px;
width: 40%;
line-height: 30px;
position: absolute;
top: 0;
right: 0;
}
}
}
</style>
Dayjs
安装
npm install dayjs --save
main.js 引用:
import dayjs from 'dayjs'
Vue.prototype.dayjs = dayjs;
获取当前时间
<template>
<div id="app">
{{this.datetime}}
</div>
</template>
<script>
export default {
name: "app",
data() {
return {
timer: '',
datetime: ''
}
},
mounted() {
this.timer = setInterval(() => {
this.datetime = this.dayjs().format("YYYY-MM-DD HH:mm:ss")
}, 1000)
},
beforeDestroy() {
if(this.timer){
clearInterval(this.timer);
}
}
};
</script>
<style lang="scss" scoped>
</style>
时间戳转时间
//HTML
// :formatter="dateFormat"
<el-table-column prop="add_time"
:formatter="dateFormat" label="创建时间" width="180">
</el-table-column>
//js
mothods:{
dateFormat(row, column){
var date = row[column.property];
return this.day(date).format('YYYY-MM-DD');
//return this.day(date*1000).format('YYYY-MM-DD');
},
}
至于遇到总是输入1970年,大部分是你拿到的时间戳是十位数的,
输出的是秒,所以只需要把时间戳*1000就可以输出当前时间