首先写一个函数将日期转成你想要的格式
function timeToStr (time) {
const Y = time.getFullYear() + '-'
const M = (time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1) + '-'
const D = (time.getDate() < 10 ? '0' + (time.getDate()) : time.getDate()) + ' '
return Y + M + D
}
js获取某个日期 n天之后的日期、n月之后的日期:
/* params:
* startTime --- 指定日期
* AddCount --- 指定天/月数
* dayFlag --- true为n天,false为n月
* */
function getDateStr (startTime, AddCount, dayFlag) {
const dd = new Date(startTime)
// 获取AddCount天、月后的日期
if (dayFlag) {
dd.setDate(dd.getDate() + AddCount)
} else {
dd.setMonth((dd.getMonth() - 1) + AddCount)
}
return timeToStr(dd)
}
js获取某月最后一天的日期:
function getLastDayOfMonth (time) {
const dd = new Date(time)
const curMonth = dd.getMonth()
// 生成实际的月份: 由于curMonth会比实际月份小1, 故需加1
dd.setMonth(curMonth + 1)
// 将日期设置为0, 返回当月最后一天日期, 将日期设置为1,返回下一个月第一天日期
dd.setDate(0)
return timeToStr(dd)
}
js获取某周周一和周日的日期:
function getWeekStartAndEnd (time) {
// 起止日期数组
let startStop = []
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24
let currentDate = new Date(time)
// 相对于当前日期AddWeekCount个周的日期
currentDate = new Date(currentDate.getTime())
// 返回date是一周中的某一天
const week = currentDate.getDay()
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6
// 获得该周的第一天
const currentWeekFirstDay = new Date(currentDate.getTime() - (millisecond * minusDay))
// 获得该周的最后一天
const currentWeekLastDay = new Date(currentWeekFirstDay.getTime() + (millisecond * 6))
// 添加至数组
startStop.push(timeToStr(currentWeekFirstDay))
startStop.push(timeToStr(currentWeekLastDay))
return startStop
}