可以在utils.js里面封装通用方法,引入即可使用。
/* 获取本月初跟月底*/
export const getCurrentMonth = () => {
// 2021-10-01 00:00:00
let firstDate = new Date();
let startDate =
firstDate.getFullYear() +
"-" +
(firstDate.getMonth() + 1 < 10 ? "0" : "") +
(firstDate.getMonth() + 1) +
"-" +
"01" +
" " +
"00:00:00";
let date = new Date();
let currentMonth = date.getMonth();
let nextMonth = ++currentMonth;
let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
let oneDay = 1000 * 60 * 60 * 24;
let lastDate = new Date(nextMonthFirstDay - oneDay);
let endDate =
lastDate.getFullYear() +
"-" +
(lastDate.getMonth() + 1 < 10 ? "0" : "") +
(lastDate.getMonth() + 1) +
"-" +
(lastDate.getDate() < 10 ? "0" : "") +
lastDate.getDate() +
" " +
"00:00:00";
let resTime = {
startDate,
endDate,
};
return resTime;
};
/* 获取距离现在的前一天*/
export const getNowAgoFormatDate = () => {
Date.prototype.format = function (format) {
var args = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
S: this.getMilliseconds(),
};
if (/(y+)/.test(format))
format = format.replace(
RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length)
);
for (var i in args) {
var n = args[i];
if (new RegExp("(" + i + ")").test(format))
format = format.replace(
RegExp.$1,
RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length)
);
}
return format;
};
var curDate = new Date();
var stringDate = new Date(curDate.getTime() - 24 * 60 * 60 * 1000).format(
"yyyy-MM-dd hh:mm:ss"
);
return stringDate;
};