1.在根目录创建目录components
2.在components组件中创建time.js
js中编写
const DateTime = (date = new Date()) => {
//不传date则默认当前时间
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
// 不足两位,添“0”
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
minute = minute < 10 ? '0' + minute : minute;
second = second < 10 ? '0' + second : second;
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
};
export default DateTime
3.在需要获取当前时间的页面引入js
import dateTime from '@/components/time.js';
4.可以直接调取,引用
onLoad() {
console.log(dateTime());
},