那如何得到某一天所在星期的开始和结束日期?

该代码段定义了一个JavaScript函数getWeekStartAndEnd,用于获取当前周的开始和结束日期。当遇到今天是周日(getDay()返回0)时,进行了特殊处理,确保正确返回上周的周一和本周的周日。通过添加一个条件,如果todayDay为0,则强制设为7,从而解决了周日的边界问题。
摘要由CSDN通过智能技术生成
function getWeekStartAndEnd() {
    const oneDayTime = 1000 * 60 * 60 * 24; // 一天里一共的毫秒数
    const today = new Date();
    const todayDay = today.getDay(); // 获取今天是星期几,假设是周3
    const startDate = new Date(
        today.getTime() - oneDayTime * (todayDay - 1)
    );
    const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));
 
    return { startDate, endDate };
}
const week = getWeekStartAndEnd();
console.log(week.startDate, week.endDate);

但是当今天是周日的时候today是0

改善一下

function getWeekStartAndEnd(timestamp) {
    const oneDayTime = 1000 * 60 * 60 * 24; // 一天里一共的毫秒数
    const today = timestamp ? new Date(timestamp) : new Date();
    const todayDay = today.getDay() || 7; // 若那一天是周末时,则强制赋值为7
    const startDate = new Date(
        today.getTime() - oneDayTime * (todayDay - 1)
    );
    const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));
 
    return { startDate, endDate };
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值