在 vue 中获取当前年月日的方法有:直接获取当前时间戳;使用 new date() 对象;使用 moment.js 库;使用 vue 的内置过滤器。

如何在 Vue 中获取当前年月日
直接获取当前时间戳
<code class="javascript">const timestamp = Date.now();</code>
使用 new Date() 对象
<code class="javascript">const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; // 注意:月份是从 0 开始的 const day = now.getDate();</code>
使用 moment.js 库
立即学习“前端免费学习笔记(深入)”;
<code class="javascript">import moment from "moment"; const now = moment(); const year = now.year(); const month = now.month() + 1; const day = now.date();</code>
使用 Vue 的内置过滤器
<code class="html">{{ new Date() | formatDate("yyyy-MM-dd") }}</code>其中,formatDate 是 Vue 提供的内置过滤器,可将日期格式化为指定格式。
例子
如需在 Vue 组件中获取当前年月日,可以使用以下代码:
<code class="vue"><script>
export default {
data() {
return {
now: new Date(),
};
},
};
</script>
<template>
<span>{{ now.getFullYear() }}年{{ now.getMonth() + 1 }}月{{ now.getDate() }}日</span>
</template></code>










