js常用方法-获取当前时间
vue项目全局公共方法,可以直接调用;
vue项目中main.js引入
1 import myUtils from './utils/myUtils'; 2 3 4 /* 将 myUtils 挂载到 vue 的原型上 */ 5 Vue.prototype.myUtils = myUtils;
封装方法
1 /** 2 * 获取当前时间---年月日时分秒 3 * @param format(是否精确到时分秒)、type(分隔符) 4 * @returns {number} 5 */ 6 static getCurrentDate(format, type) { 7 let now = new Date(); 8 let year = now.getFullYear(); // 得到年份 9 let month = now.getMonth(); // 得到月份 10 let date = now.getDate(); // 得到日期 11 12 // let day = now.getDay();// 得到周几 13 let hour = now.getHours(); // 得到小时 14 let minu = now.getMinutes(); // 得到分钟 15 let sec = now.getSeconds(); // 得到秒 16 month = month + 1; 17 if (month < 10) { 18 month = '0' + month; 19 } 20 if (date < 10) { 21 date = '0' + date; 22 } 23 if (hour < 10) { 24 hour = '0' + hour; 25 } 26 if (minu < 10) { 27 minu = '0' + minu; 28 } 29 if (sec < 10) { 30 sec = '0' + sec; 31 } 32 let time = ''; 33 34 // 精确到天 35 if (format === 1) { 36 time = year + type + month + type + date; 37 } else { 38 39 // 精确到时分秒 40 time = year + type + month + type + date + ' ' + hour + ':' + minu + ':' + sec; 41 } 42 return time; 43 }
调用
1 let time = this.myUtils.getCurrentDate(1,'-'); 2 console.log('时间---',time);

浙公网安备 33010602011771号