Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if date is in this week in javascript?

I have this date "2016-04-23T11:45:00Z" and I want to check this date in this week or not ?

Thanks,

like image 447
Sophon Men Avatar asked Nov 30 '22 16:11

Sophon Men


2 Answers

Dates are hard, I would always suggest using a library dedicated to date handling as it reduces the chances of errors in your code.

MomentJS is a good one.

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

Edit: Please note as of 2020 moment may not be a good choice for new projects

like image 182
Jamiec Avatar answered Dec 04 '22 09:12

Jamiec


This seems to be working for me.

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);
like image 39
Michael Lynch Avatar answered Dec 04 '22 09:12

Michael Lynch