vue页面
<template>
<div>
<h3>当前时间</h3>
<p>{{ nowtime }}</p>
<el-divider></el-divider>
<h3>当前时间戳(毫秒)</h3>
<p>{{ nowtimestamp }}</p>
<el-divider></el-divider>
<h3>当前时间戳(秒)</h3>
<p>{{ nowtimestamp / 1000 }}</p>
<el-divider></el-divider>
<h3>时间戳转日期</h3>
<p>{{ stamptodate }}</p>
<el-divider></el-divider>
<h3>日期转时间戳(毫秒)</h3>
<p>{{ datetostamp }}</p>
<el-divider></el-divider>
<h3>日期转时间戳(秒)</h3>
<p>{{ datetostamp / 1000 }}</p>
</div>
</template>
<script>
import timer from "../components/timer";
export default {
data() {
return {
nowtime: "",
nowtimestamp: "",
stamptodate: "",
datetostamp: "",
};
},
components: { timer },
methods: {},
mounted() {
//当前时间
this.nowtime = timer.getdate();
//当前时间戳(毫秒)
this.nowtimestamp = new Date(this.nowtime).getTime();
//时间戳转日期
this.stamptodate = timer.getdate(1679293297000);
//日期转时间戳
this.datetostamp = new Date("2023-03-20 14:24:46").getTime();
},
};
</script>
<style>
</style>
组件
const timer = {
getdate(timestamp) {
//有参数就转日期,没有参数就获取当前日期
let newDate = timestamp ? new Date(timestamp) : new Date()
let year = newDate.getFullYear()
let month = newDate.getMonth() + 1
month = month < 10 ? '0' + month : month
let day = newDate.getDate()
day = day < 10 ? '0' + day : day
let hour = newDate.getHours()
hour = hour < 10 ? '0' + hour : hour
let min = newDate.getMinutes()
min = min < 10 ? '0' + min : min
let seconds = newDate.getSeconds()
seconds = seconds < 10 ? '0' + seconds : seconds
return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + seconds
},
}
export default timer;