获取当前日期前后某年/月/日/时/分/秒的日期
/*
* 获取当前时间或者,某个时间
* time - 某个时刻, 默认当前时间
* type - year/mnth/day/hours/minutes/seconds
* num - 某个时间之前或者之后几年/月/日/时/分/秒的Date; 整数
*/
function getTimeCustom (time, type = 'day', num) {
const date = time ? new Date(time) : new Date()
if (type === 'year') {
date.setFullYear(date.getFullYear() + num)
} else if (type === 'month') {
date.setMonth(date.getMonth() + num)
} else if (type === 'day') {
date.setDate(date.getDate() + num)
} else if (type === 'hours') {
date.setHours(date.getHours() + num)
} else if (type === 'minutes()') {
date.setMinutes(date.getMinutes() + num)
} else if (type === 'seconds') {
date.setSeconds(date.getSeconds() + num)
}
return date
}
获取当前月或者前后某月开始结束日期
转自blog.csdn.net/WICHER_WU/a… ;然后并稍加修改
/**
*获得距离当前前后某月的开始日期和结束日期
* month 整数,负数当前之前某月,正数当月之后某月,0当月
*/
function getMonthStartDateAndDateRange (month = 0) {
const oneDayLong = 24 * 60 * 60 * 1000
const now = new Date()
now.setMonth(now.getMonth() + month)
const year = now.getFullYear()
const monthStartDate = new Date(year, now.getMonth(), 1) // 当前月1号
const nextMonthStartDate = new Date(year, now.getMonth() + 1, 1) // 下个月1号
const days = (nextMonthStartDate.getTime() - monthStartDate.getTime()) / oneDayLong // 计算当前月份的天数
const monthEndDate = new Date(year, now.getMonth(), days)
const monthRange = [monthStartDate, monthEndDate]
return monthRange
}
获取当前周或者前后某周开始结束日期
/**
* 获得本周的开始日期和结束日期
*/
function getWeekStartDateAndEndDateRange () {
const oneDayLong = 24 * 60 * 60 * 1000
const now = new Date()
const mondayTime = now.getTime() - (now.getDay() - 1) * oneDayLong
const sundayTime = now.getTime() + (7 - now.getDay()) * oneDayLong
const monday = new Date(mondayTime)
const sunday = new Date(sundayTime)
const weekRange = [monday, sunday]
return weekRange
}