简体   繁体   中英

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,

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

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);
<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">

    <h1>{{currentDate}}</h1>
    <h1>{{numberCurrentDateWeeks}}</h1>

    <h1>{{yourDate}}</h1>
    <h1>{{numberYourDateWeeks}}</h1>

 </div>
</div>

......

angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$filter", function(s, $filter) {
  s.yourDate = '2016-04-23T11:45:00Z'
  s.currentDate = new Date();

  s.numberCurrentDateWeeks = $filter('date')(s.currentDate, "w");
  s.numberYourDateWeeks = $filter('date')(s.yourDate, "w");

}]);

then you got the Week numbers just compare or do whatever you like

cheers !

May not be the most optimal solution, but I think it's quite readable:

function isThisWeek (date) {
  const now = new Date();

  const weekDay = (now.getDay() + 6) % 7; // Make sure Sunday is 6, not 0
  const monthDay = now.getDate();
  const mondayThisWeek = monthDay - weekDay;

  const startOfThisWeek = new Date(+now);
  startOfThisWeek.setDate(mondayThisWeek);
  startOfThisWeek.setHours(0, 0, 0, 0);

  const startOfNextWeek = new Date(+startOfThisWeek);
  startOfNextWeek.setDate(mondayThisWeek + 7);

  return date >= startOfThisWeek && date < startOfNextWeek;
}

You can do that without any libraries by checking if the date.getTime() (milliseconds since epoch) is between last monday and next monday:

const WEEK_LENGTH = 604800000;

function onCurrentWeek(date) {

    var lastMonday = new Date(); // Creating new date object for today
    lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay()-1)); // Setting date to last monday
    lastMonday.setHours(0,0,0,0); // Setting Hour to 00:00:00:00
    


    const res = lastMonday.getTime() <= date.getTime() &&
                date.getTime() < ( lastMonday.getTime() + WEEK_LENGTH);
    return res; // true / false
}

(one week in ms = 24 * 60 * 60 * 1000 * 7 = 604,800,000)

This link explaines, how to do this without using any js libraries. https://gist.github.com/dblock/1081513

Code against link death:

function( d ) { 

  // Create a copy of this date object  
  var target  = new Date(d.valueOf());  

  // ISO week date weeks start on monday  
  // so correct the day number  
  var dayNr   = (d.getDay() + 6) % 7;  

  // Set the target to the thursday of this week so the  
  // target date is in the right year  
  target.setDate(target.getDate() - dayNr + 3);  

  // ISO 8601 states that week 1 is the week  
  // with january 4th in it  
   var jan4    = new Date(target.getFullYear(), 0, 4);  

  // Number of days between target date and january 4th  
  var dayDiff = (target - jan4) / 86400000;    

  // Calculate week number: Week 1 (january 4th) plus the    
  // number of weeks between target date and january 4th    
  var weekNr = 1 + Math.ceil(dayDiff / 7);    

  return weekNr;    

}

I managed to do it with this simple trick and without any external library. Considering monday as the first day of the week, the function takes as parameter a date string and do the validation before checking if the day indeed is in the current week.

  function isInThisWeek(livr){
const WEEK = new Date()

// convert delivery date to Date instance
const DATEREF = new Date(livr)

// Check if date instance is in valid format (depends on the function arg) 
if(DATEREF instanceof Date && isNaN(DATEREF)){ 
  console.log("invalid date format")
  return false}

// Deconstruct to get separated date infos
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]

// get Monday date 
const monday = (WEEK.getDate() - WEEK.getDay()) + 1

// get Saturday date
const sunday = monday + 6

// Start verification
if (yearR !== WEEK.getFullYear())  { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}

}

In the comments I saw that you stated that your week starts on Monday .

In that case, I guess it'd be a good idea to calculate the ISO week number of the 2 dates and see if you get the same week number for both of them.

To calculate the ISO week number , check this answer:

In case anyone else's week starts on Sunday instead, you can use this answer to calculate the week number accordingly.

then you can do something like this:

function isSameWeek(date1, date2) {
   return date1.getWeekNumber() === date2.getWeekNumber();
}
const isDateInThisWeek = (date) => {
  const today = new Date();
  
  //Get the first day of the current week (Sunday)
  const firstDayOfWeek = new Date(
    today.setDate(today.getDate() - today.getDay())
  );

  //Get the last day of the current week (Saturday)
  const lastDayOfWeek = new Date(
    today.setDate(today.getDate() - today.getDay() + 6)
  );

  //check if my value is between a minimum date and a maximum date
  if (date >= firstDayOfWeek && date <= lastDayOfWeek) {
    return true;
  } else {
    return false;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM