<template>
<div>
{{ formatDate(date) }}
</div>
</template>
<script>
export default {
data() {
return {
date: new Date()
};
},
methods: {
formatDate(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
}
};
</script>
只需要获取小时、分钟和秒拼接上就可以
formatDate(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hour = date.getHours().toString().padStart(2, '0');
const minute = date.getMinutes().toString().padStart(2, '0');
const second = date.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
tip:分割获取的时间保留年月日,方法很多,记录常用的slice方法
var dateStr = "2023-05-19 09:30:57";
console.log(dateStr.slice(0, 10)); // 输出:2023-05-19
时间操作比较常用记录一下