如何在javascrip中检查日期是否在本周?

ycggw6v2  于 2022-09-18  发布在  Java
关注(0)|答案(2)|浏览(143)

我有一个日期“2016-04-23T11:45:00Z”,我想把这个日期登记在这个星期吗?

谢谢,

ql3eal8s

ql3eal8s1#

日期是困难的,我总是建议使用专门用于日期处理的库,因为它降低了代码中出错的可能性。

MomentJS是一个很好的选择。

var now = moment();
var input = moment("2016-04-17T11:45:00Z");
var isThisWeek = (now.isoWeek() == input.isoWeek())

编辑:请注意,截至2020年,Moment可能不是新项目的良好选择

d7v8vwbk

d7v8vwbk2#

这似乎对我很管用。

function isDateInThisWeek(date) {
  const todayObj = new Date();
  const todayDate = todayObj.getDate();
  const todayDay = todayObj.getDay();

  // get first date of week
  const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));

  // get last date of week
  const lastDayOfWeek = new Date(firstDayOfWeek);
  lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);

  // if date is equal or within the first and last dates of the week
  return date >= firstDayOfWeek && date <= lastDayOfWeek;
}

const date = new Date();
const isInWeek = isDateInThisWeek(date);

相关问题