js查询最近一个月,最近一周,本月,本年,上月,上年
<el-select
v-model="value"
placeholder="请选择"
@change="getDateInput"
>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
>
</el-option>
</el-select>
js部分
value: "",
options: [
{ value: "", label: "最近一个月" },
{
value: 1,
label: "最近一周",
},
{
value: 2,
label: "本月",
},
{
value: 3,
label: "本年",
},
{
value: 4,
label: "上月",
},
{
value: 5,
label: "上年",
},
],
getLastTime(value) {
console.log(value);
let now = new Date(); //当前日期
let year = now.getFullYear(); //当前年
let month = now.getMonth() + 1; //0-11表示1-12月
let day = now.getDate(); //当前日
let dateObj = {};
dateObj.now = year + "-" + month + "-" + day;
let nowMonthDay = new Date(year, month, 0).getDate(); // 获取当年月份的最后一天
let currentYearFirstDate = new Date(year, 0, 1); // 获取今年日期格式
console.log(currentYearFirstDate);
let partiYear = currentYearFirstDate.getFullYear(); // 获取今年格式
let partiMonth = currentYearFirstDate.getMonth() + 1; // 获取月格式
let partiDay = currentYearFirstDate.getDate(); // 获取日格式
this.endTime = dateObj.now;
let startMonthDay = new Date(year, parseInt(month) - 1, 0).getDate(); // 获取上一个月的月底
if (value === undefined || value === "") {
// 最近一月
if (month - 1 <= 0) {
dateObj.start = year - 1 + "-" + 12 + "-" + day;
} else {
if (startMonthDay < day) {
if (day < endMonthDay) {
dateObj.start =
year +
"-" +
(month - 1) +
"-" +
(startMonthDay - (endMonthDay - day));
} else {
dateObj.start = year + "-" + (month - 1) + "-" + startMonthDay;
}
} else {
dateObj.start = year + "-" + (month - 1) + "-" + day;
}
}
this.startTime = dateObj.start;
} else if (value === 1) {
// 最近一周
if (day - 7 <= 0) {
if (month - 1 <= 0) {
dateObj.start = year - 1 + "-" + 12 + "-" + (31 - (7 - day));
} else {
dateObj.start =
year + "-" + (month - 1) + "-" + (startMonthDay - (7 - day));
}
} else {
dateObj.start = year + "-" + month + "-" + (day - 7);
}
this.startTime = dateObj.start;
} else if (value === 2) {
dateObj.now = year + "-" + month + "-" + day;
dateObj.start = year + "-" + month + "-1";
this.endTime = dateObj.now;
this.startTime = dateObj.start;
console.log(dateObj);
} else if (value === 3) {
// 本年
dateObj.start = partiYear + "-" + partiMonth + "-" + partiDay;
this.endTime = dateObj.now;
this.startTime = dateObj.start;
console.log(dateObj);
} else if (value === 4) {
let mewMonth = now.getMonth();
console.log(mewMonth);
if (mewMonth === 0) {
mewMonth = 12;
year = year - 1;
}
dateObj.start = year + "-" + mewMonth + "-1";
dateObj.end = year + "-" + month + "-" + "01"; //上个月的第一天
console.log(dateObj);
this.endTime = dateObj.end;
this.startTime = dateObj.start;
} else if (value === 5) {
dateObj.start = partiYear - 1 + "-" + partiMonth + "-" + partiDay;
dateObj.end = partiYear + "-" + partiMonth + "-" + partiDay;
this.endTime = dateObj.end;
this.startTime = dateObj.start;
}
},