1、获取当前年月日时间

getCurrentDate() {const date = new Date();const year = date.getFullYear();const month = date.getMonth() + 1; // JavaScript的月份是从0开始的,所以需要加1const day = date.getDate();const hours = date.getHours().toString().padStart(2, '0'); // 补零const minutes = date.getMinutes().toString().padStart(2, '0'); // 补零this.currentDate = `${year}-${month}.${day}-${hours}:${minutes}`;},

2、将时间戳转换为指定格式

function formatTime(time, format) {const date = new Date(time);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');let result = '';switch (format) {case 'yyyy-MM-dd':result = `${year}-${month}-${day}`;break;case 'yyyy/MM/dd':result = `${year}/${month}/${day}`;break;case 'yyyy年MM月dd日':result = `${year}年${month}月${day}日`;break;case 'HH:mm:ss':result = `${hour}:${minute}:${second}`;break;default:result = `${year}-${month}-${day} ${hour}:${minute}:${second}`;}return result;}

3.vue中时间转换插件:moment.js

官网:Moment.js 中文网

(1)下载安装包

npm installmoment–save

(2)在main.js中引入

import moment from ‘moment’
Vue.prototype.$moment = moment

(3)使用

this.$moment(‘需要转换的时间’).format(‘YYYY-MM-DD’)