How to calculate the date of the current week in js

You can use JavaScript's Date object to calculate the current day of the week. First, you need to get the current date, and then use the getDay method of the Date object to get the day of the week (Sunday is 0, Monday is 1, and so on). You can then calculate the dates of the first and last day of the week based on what day of the week it is.

For example, here is a sample function that calculates the first and last days of the current week:
 

function getWeekDates () {
  // 获取当前日期
  var today = new Date();
  // 获取当前是星期几
  var day = today.getDay();
  if (day == 0) {
    // 计算本周第一天的日期
    var startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day - 6);
    // 计算本周最后一天的日期
    var endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day);
  } else {
    var startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day + 1);
    var endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day + 7);
  }
  // 返回本周的日期范围
  return { start: startDate, end: endDate };
}

Guess you like

Origin blog.csdn.net/melissaomy/article/details/132066089