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

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










