The new requirements of the project obtain the time period of the week before the current time, January, March, June, and one year:
Get the time period of the last week
// 获取近一周时间
export function getLastWeek() {
var now = new Date()
var year = now.getFullYear()
var month = now.getMonth() + 1 //0-11表示1-12月
var day = now.getDate()
var dateObj = {
}
dateObj.endTime = year + "-" + month + "-" + day
if (day - 7 <= 0) {
//如果在当月7日之前
var endTimeMonthDay = new Date(year, parseInt(month) - 1, 0).getDate() //1周前所在月的总天数
if (month - 1 <= 0) {
//如果在当年的1月份
dateObj.startTime = year - 1 + "-" + 12 + "-" + (31 - (7 - day))
} else {
dateObj.startTime = year + "-" + (month - 1) + "-" + (endTimeMonthDay - (7 - day))
}
} else {
dateObj.startTime = year + "-" + month + "-" + (day - 7)
}
return dateObj
}
Printing found that the time a week ago was added to the number of days today, and one day was added, and a new one was written
/**
* 获取近多少天时间
* @returns
*/
export function getNumDaysAgo(n) {
let num = n - 1 // 天数需要包含今天
var now = new Date()
var year = now.getFullYear()
var month = now.getMonth() + 1
var day = now.getDate()
var dateObj = {
}
if (day - num <= 0) {
//如果在当月num日之前
var endTimeMonthDay = new Date(year, parseInt(month) - 1, 0).getDate() //1周前所在月的总天数
if (month - 1 <= 0) {
//如果在当年的1月份
dateObj.startTime = year - 1 + "-" + 12 + "-" + (31 - (num - day))
} else {
dateObj.startTime = year + "-" + (month - 1) + "-" + (endTimeMonthDay - (num - day))
}
} else {
dateObj.startTime = year + "-" + month + "-" + (day - num)
}
dateObj.endTime = year + "-" + month + "-" + day
return dateObj
}
Get previous months time period
Get the current day when the passed parameter is 0
// 获取近i月的时间段
export function getLastMonth(i) {
console.log("获取近i月的时间段", i)
var now = new Date()
var year = now.getFullYear()
var month = now.getMonth() + 1
var day = now.getDate()
var dateObj = {
}
dateObj.endTime = year + "-" + month + "-" + day
var nowMonthDay = new Date(year, month, 0).getDate() //当前月的总天数
if (i == 12) {
//如果是12月,年数往前推一年<br>
dateObj.startTime = year - 1 + "-" + month + "-" + day
} else if (month - i <= 0) {
// 如果前推i月小于0,年数往前推一年<br>
dateObj.startTime = year - 1 + "-" + 12 + "-" + day
} else {
var endTimeMonthDay = new Date(year, parseInt(month) - i, 0).getDate()
if (endTimeMonthDay < day) {
// i个月前所在月的总天数小于现在的天日期
if (day < nowMonthDay) {
// 当前天日期小于当前月总天数
dateObj.startTime = year + "-" + (month - i) + "-" + (endTimeMonthDay - (nowMonthDay - day))
} else {
dateObj.startTime = year + "-" + (month - i) + "-" + endTimeMonthDay
}
} else {
dateObj.startTime = year + "-" + (month - i) + "-" + day
}
}
return dateObj
}