user366123
user366123

Reputation: 153

How to check if Array of dates fall under current week

I'm using Moment.js to generate an Array of dates for current week.

Then i'm getting an Array of dates from system, now i want to check if any of these dates match against the Moment.js created current week.

If yes, then i would like to return their values( 0,1,2.. so i can manipulate the dom objects accordingly. (Example: if the match returns Sunday and Tuesday of current week then i would highlight them)

I've only gone so far it getting a single hard coded value to return true or false if the date falls under current week.

var REFERENCE = moment();
var startOfWeek = REFERENCE.clone().startOf('week');

var endOfWeek = REFERENCE.clone().endOf('week');
var highlightDays = ['2017-08-23','2017-08-25','2017-08-29']; //highlight respective days ONLY they fall under current week

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.toDate());
    day = day.clone().add(1, 'd');
}


function isWithinThisWeek(momentDate) {
    return momentDate.isBetween(startOfWeek, endOfWeek);

}


console.log("is it within this week?  "+isWithinThisWeek(moment("2017-08-25")));

jsfiddle

Upvotes: 0

Views: 711

Answers (4)

VincenzoC
VincenzoC

Reputation: 31502

You can use jQuery Attribute Equals Selector [name="value"] and moment format() to highlight the dates in the current week of the highlightDays array.

Using dddd token in format() you will get Sunday Monday ... Friday Saturday, that are the values of your data-day attribute.

EDIT: The problem was the isWithinThisWeek method that gave wrong result for Sunday, because, as docs states:

Check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc). The match is exclusive.

Then you can use both:

Here a live example:

var REFERENCE = moment(); 
var startOfWeek = REFERENCE.clone().startOf('week');
var endOfWeek = REFERENCE.clone().endOf('week');
var highlightDays = ['2017-08-18','2017-08-19','2017-08-20','2017-08-21','2017-08-22','2017-08-23','2017-08-24','2017-08-25','2017-08-26']; //highlight respective days ONLY they fall under current week

var days = [];
var day = startOfWeek;

while ( day.isBefore(endOfWeek) ) {
    days.push(day.toDate());
    day = day.clone().add(1, 'd');
}

function isWithinThisWeek(momentDate) {
    return momentDate.isBetween(startOfWeek, endOfWeek, null, '[]');
    // return momentDate.isSame(REFERENCE, 'week')
}

for(var i=0; i<highlightDays.length; i++){
  var m = moment(highlightDays[i]);
    if( isWithinThisWeek(m) ){
    var dayName = m.format('dddd').toLowerCase();
    $("[data-day='"+dayName+"']").addClass("highlight");
  }
}
.highlight{
  background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<table class="table">
  <tbody>
    <tr>
      <td data-day="sunday">Sunday</td>
    </tr>
    <tr>
      <td data-day="monday">Monday</td>
    </tr>
    <tr>
      <td data-day="tuesday">Tuesday</td>
    </tr>
    <tr>
      <td data-day="wednesday">Wednesday</td>
    </tr>
    <tr>
      <td data-day="thursday">Thursday</td>
    </tr>
    <tr>
      <td data-day="friday">Friday</td>
    </tr>
    <tr>
      <td data-day="saturday">Saturday</td>
    </tr>
  </tbody>
</table>

My answer is similar to the two already posted but:

  • I do not use the numToDays temp array
  • I do not rely on the order of the elements in the HTML

Upvotes: 1

hallleron
hallleron

Reputation: 1992

EDIT: Fixed the highlighting bug for Sunday. You had to subtract one day from startOfWeek in the isBetween() call.

I think this is what you want:

var REFERENCE = moment(); 
var startOfWeek = REFERENCE.clone().startOf('week');
var endOfWeek = REFERENCE.clone().endOf('week');
var highlightDays = ['2017-08-20','2017-08-21','2017-08-22','2017-08-23','2017-08-24','2017-08-25','2017-08-26'];

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.toDate());
    day = day.clone().add(1, 'd');
}

function isWithinThisWeek(momentDate) {
    return momentDate.isBetween(startOfWeek.subtract(1, 'd'), endOfWeek.add(1, 'd'));  
}

for(var i = 0; i < highlightDays.length; i++){
console.log(isWithinThisWeek(moment(highlightDays[i])));
  if(isWithinThisWeek(moment(highlightDays[i]))){
    var date_converted = new Date(highlightDays[i]);
    $(".table td:eq("+date_converted.getDay()+")").addClass("highlight");
  }
}
.highlight{
  background:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
		<tbody>
		<tr>
			<td data-day="sunday">Sunday</td>
		</tr>
<tr>
			<td data-day="monday">Monday</td>
		</tr>
<tr>
			<td data-day="tuesday">Tuesday</td>
		</tr>
<tr>
			<td data-day="wednesday">Wednesday</td>
		</tr>
<tr>
			<td data-day="thursday">Thursday</td>
		</tr>
<tr>
			<td data-day="friday">Friday</td>
		</tr>
<tr>
	  <td data-day="saturday">Saturday</td>
</tr>
		</tbody>
		</table>

I added a for() loop at the end and check if the date is in current week by using your function. Using this I use addClass() to highlight the matching records.

Upvotes: 1

riot
riot

Reputation: 76

I'm not confident with Moment.js, but i'll give it a try with plain JS. Maybe this helps.

var highlightDays = ['2017-08-23','2017-08-25','2017-08-29']; //highlight respective days ONLY they fall under current week
var date= new Date(); //Today Date
var today = date.getDay(); //Today Day of the week Number
var dayMSec = 1000 * 60 * 60 * 24; //a day in ms
var weekMSec = dayMSec * 7; // a week in ms

//Here i calculate the start of the week timestamp(Using dates the starting day will be Sunday). TS in in ms
var startWeekTS = date.getTime() - (dayMSec * today); 

highlightDays.forEach(function(val, index){
  if(isWithinThisWeek(val)){
    //just logging
    console.log(highlightDays[index] + ' is within this week');
  }
});


function isWithinThisWeek(date) {
    //generate a Date() from passed arg
    date = new Date(date);
    //getting the ts of the date
    var dateMSec = date.getTime();
    //subtracting start of the week ts and arg ts
    var tsDiff = dateMSec - startWeekTS;
    
    //if ts is between 0 and a week expressed in ms
    if( tsDiff >= 0  && tsDiff< weekMSec){
      //here we go
      return true;
    }
    
    //nope
    return false;
}

Upvotes: 0

Deckerz
Deckerz

Reputation: 2604

Here is what you are after. I added a foreach loop and a simple array of days to convert int to the day name. Then it selects the td based of the data-day and highlights it.

var REFERENCE = moment(); 
var startOfWeek = REFERENCE.clone().startOf('week');
var endOfWeek = REFERENCE.clone().endOf('week');
var highlightDays = ['2017-08-23','2017-08-25','2017-08-29']; //highlight respective days ONLY they fall under current week

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.toDate());
    day = day.clone().add(1, 'd');
}


function isWithinThisWeek(momentDate) {
    return momentDate.isBetween(startOfWeek, endOfWeek);
}

var numToDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

highlightDays.forEach(function(element) {
  if(isWithinThisWeek(moment(element))){
  	var date = moment(element);    
    var day = date.format("d");
    $("td[data-day='"+numToDays[day]+"']").addClass("highlight");
  }
});
.highlight{
  background:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
		<tbody>
		<tr>
			<td data-day="sunday">Sunday</td>
		</tr>
<tr>
			<td data-day="monday">Monday</td>
		</tr>
<tr>
			<td data-day="tuesday">Tuesday</td>
		</tr>
<tr>
			<td data-day="wednesday">Wednesday</td>
		</tr>
<tr>
			<td data-day="thursday">Thursday</td>
		</tr>
<tr>
			<td data-day="friday">Friday</td>
		</tr>
<tr>
	  <td data-day="saturday">Saturday</td>
</tr>
		</tbody>
		</table>

Upvotes: 0

Related Questions