1. 在util里新建一个date.js 赋值以下代码
//补零
function doHandleMonth(month) {
var m = month;
if (month.toString().length == 1) {
m = "0" + month;
}
return m;
}
// 格式化日期: yyyy-MM-dd
function formatDate(date) {
const year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
if (month < 10) {
month = `0${month}`
}
if (day < 10) {
day = `0${day}`
}
return (`${year}-${month}-${day}`)
}
// 近X天
export function getDay(day) {
var today = new Date();
var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds);
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
tMonth = doHandleMonth(tMonth + 1);
tDate = doHandleMonth(tDate);
return tYear + "-" + tMonth + "-" + tDate;
}
// 本月
export function getNowMonth() {
var today = new Date();
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
tMonth = doHandleMonth(tMonth + 1);
tDate = "01"
return tYear + "-" + tMonth + "-" + tDate;
}
// 上月日期
export function getLastMonth() {
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth()
const lastMonthStartDate = formatDate(new Date(year, month - 1, 1))
const lastMonthEndDate = formatDate(new Date(year, month, 0))
const lastMonth = []
lastMonth.push(lastMonthStartDate, lastMonthEndDate)
return lastMonth
}
2.在需要使用的页面引入
import {
getDay,
getNowMonth,
getLastMonth
} from "@/util/date.js"
3.使用
switch (index) {
case 0:
this.endDate = nowData
this.startDate = nowData //今天
break;
case 1:
this.endDate = getDay(-1)
this.startDate = getDay(-1) //昨天
break;
case 2:
this.endDate = nowData
this.startDate = getDay(-7) //近7天
break;
case 3:
this.endDate = nowData
this.startDate = getDay(-30) //近30
break;
case 4:
this.endDate = nowData
this.startDate = getNowMonth() //本月
break;
case 5:
this.endDate = getLastMonth()[1]
this.startDate = getLastMonth()[0]
break;
case 6:
this.endDate = nowData
this.startDate = getDay(-365)
break;
}
本人使用场景:点击上面时间选择器 下面日期联动