js 根据日期 计算这周、月的 第一天和最后一天
/**
* 根据某一天日期 获取 当前周的第一天和最后一天的日期(周一和周日)
* @param date {Date}
* @return {{endDate: Date, startDate: Date}}
*/
export function getStartAndEndDateOfWeek(date) {
const millisecondsOfDay = 24 * 60 * 60 * 1000
let dayOfWeek = date.getDay()
if (dayOfWeek === 0) dayOfWeek = 7
const startDate = new Date(date.getTime() - (dayOfWeek - 1) * millisecondsOfDay)
const endDate = new Date(date.getTime() + (7 - dayOfWeek) * millisecondsOfDay)
return { startDate, endDate }
}
/**
* 根据某一天日期 获取 当前月的第一天和最后一天的日期
* @param date {Date}
* @return {{endDate: Date, startDate: Date}}
*/
export function getStartAndEndDateOfMonth(date) {
let year = date.getFullYear() // 2021
const month = date.getMonth() + 1 // 0 1 2 3 4 5 6 7 8 9 10 11
const startDate = new Date(year + '/' + month + '/' + 1)
let nextMonth = month + 1
if (nextMonth === 13) {
year += 1
nextMonth = 1
}
const dateLong = (new Date(year + '/' + nextMonth + '/' + 1)).getTime() - 24 * 60 * 60 * 1000
const endDate = new Date(dateLong)
return { startDate, endDate }
}
注意: 以上方法在国内使用时没问题的。如果项目会在国外使用,比如美国,有夏令时和冬令时之分,在切换时令时的那一天会多一个小时 或 少一个小时,计算日期可能就会出问题