js获取本周,本月,本季度开始结束时间
warning:
这篇文章距离上次修改已过189天,其中的内容可能已经有所变动。
// 获取本周开始和结束的日期
function getWeekDates() {
const now = new Date();
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1);
const endOfWeek = new Date(startOfWeek.getFullYear(), startOfWeek.getMonth(), startOfWeek.getDate() + 6);
return {
start: startOfWeek,
end: endOfWeek
};
}
// 获取本月开始和结束的日期
function getMonthDates() {
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
return {
start: startOfMonth,
end: endOfMonth
};
}
// 获取本季度开始和结束的日期
function getSeasonDates() {
const now = new Date();
const month = now.getMonth();
const startOfSeason = new Date(now.getFullYear(), Math.floor(month / 3) * 3, 1);
const endOfSeason = new Date(now.getFullYear(), Math.floor(month / 3) * 3 + 3, 1);
return {
start: startOfSeason,
end: new Date(endOfSeason.getTime() - 1)
};
}
// 使用示例
const weekDates = getWeekDates();
console.log('本周开始时间:', weekDates.start);
console.log('本周结束时间:', weekDates.end);
const monthDates = getMonthDates();
console.log('本月开始时间:', monthDates.start);
console.log('本月结束时间:', monthDates.end);
const seasonDates = getSeasonDates();
console.log('本季度开始时间:', seasonDates.start);
console.log('本季度结束时间:', seasonDates.end);
这段代码定义了三个函数,分别用于获取本周、本月和本季度的开始和结束日期。每个函数都返回一个包含start
和end
属性的对象,分别表示开始时间和结束时间。使用这些函数可以获取到当前时间所在周、月、季度的时间范围。
评论已关闭