【问题标题】:How to find weekends inside a date array in javascript如何在javascript中的日期数组中查找周末
【发布时间】:2022-11-25 23:53:30
【问题描述】:

我有一个日期数组,我想要用它做两件事。

1.- 告诉我其中有多少个日期是周末 2.- 使用周末日期创建新安排

我尝试了以下代码,但我不知道如何在周末为真时返回,因为您可以看到代码仅在 getDay 为 0(星期日)和 6(星期六)时计算,我必须找到一种方法来放置那些在数组中为真的

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const whenIsWeekend = [];
attendanceDates.forEach(element => {

  const date = new Date(element)
  var dayOfWeek = date.getUTCDay();
  var isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0); // 6 = Saturday, 0 = Sunday
  console.log('isWeekend', isWeekend);
  if (isWeekend) {
    whenIsWeekend.push(element)
  }
})


console.log('array of Weekend', whenIsWeekend)

console.log('count weekends', whenIsWeekend.length)

我希望返回什么

array of Weekend [
   "2022-11-26"
]
count weekends 1

提前谢谢你

【问题讨论】:

  • 我错过了什么吗,您的代码已经返回了您的内容你期待它回来吗?
  • 我有点困惑,因为你的代码有效。唯一的问题似乎是时区,因为您的 whenIsWeekend 数组可能会根据用户的时区返回错误的日期。但这可以通过使用 .getUTCDay() 而不是 .getDay() 轻松解决
  • 就是它返回的是“2022-11-21”这一天,不应该是这样的,因为日期21不是安排中的周末,周末是2022-11-26,那是他评价的使用 getDay 到“6”,这就是为什么我对这种行为感到困惑
  • @Izlia 使用.getUTCDay() 解决了这个问题。此外,您可能应该使用 .forEach() 而不是 .map()。通常你只使用 map 来修改一个数组,但在这种情况下你只是循环遍历它并将值添加到一个单独的数组。
  • 是的!就这些!我不知道时区会受到影响。管理日期让我很头疼,谢谢,给您带来的不便深表歉意!

标签: javascript arrays date find getdate


【解决方案1】:

使用本机 Javascript 日期对象:

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const weekends = attendanceDates.filter(date => {
    const dateObj = new Date(date)
    const dayOfWeek = dateObj.getUTCDay();

    if (dayOfWeek == 0 || dayOfWeek == 6) {
        return true;
    }
})

console.log(weekends) //["2022-11-26"]

使用 moment.js 库(如果你需要轻松地进行许多日期操作,这是理想的选择)

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const weekends = attendanceDates.filter(date => {
    const dateMoment = moment(date)
    if (dateMoment.day() == 0 || dateMoment.day() == 6) {
        return true;
    }
})

console.log(weekends) //["2022-11-26"]

【讨论】:

  • 完美的!就是这样,谢谢!我不知道时区会在游览时造成问题,这是我的错误
猜你喜欢
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 2021-09-09
  • 1970-01-01
相关资源
最近更新 更多