项目新需求获取当前时间前一周、一月、三月、六月、一年的时间段:
获取近一周时间段
// 获取近一周时间
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
}
打印发现获取一周前是时间加上今天天数多了一天,重新写了一个文章来源:https://uudwc.com/A/Lmkax
/**
* 获取近多少天时间
* @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
}
获取前几个月时间段
传参为0时获取当天文章来源地址https://uudwc.com/A/Lmkax
// 获取近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
}
/**
* get当月第一天
* @param {Date} date
* @returns {String} 当月第一天
*/
export function getFirstDay(date) {
const time = date ? new Date(date) : new Date()
const y = time.getFullYear()
let m = time.getMonth() + 1
const d = "01"
m = m < 10 ? "0" + m : m
return [y, m, d].join("-")
}
/**
* get当月最后一天
* @param {Date} date
* @returns {String} 当月最后一天
*/
export function getLastDay(date) {
const time = date ? new Date(date) : new Date()
const y = time.getFullYear()
let m = time.getMonth() + 1
let d = new Date(y, m, 0).getDate()
m = m < 10 ? "0" + m : m
d = d < 10 ? "0" + d : d
return [y, m, d].join("-")
}