1

Given a date in yyyy-mm-dd format, how can I determine whether a date falls in the weekend in Angular/Javascript?

$scope.isWeekend= function(){ 
  $scope.date = '2018-05-13'; 
  /* if (day(date)=='saturday' || day(date)=='sunday') { */
  alert("");
  /* } */
}
user21
  • 1,261
  • 5
  • 20
  • 41

3 Answers3

4

Use Date#getDay() to get day of week and check if it is 6 (Saturday) or 0 (Sunday):

function isWeekend(string) {
  var date = new Date(string);
  return date.getDay() === 6 || date.getDay() === 0;
}

console.log(isWeekend('2018-05-13'));
console.log(isWeekend('2018-05-12'));
console.log(isWeekend('2018-03-13'));
31piy
  • 23,323
  • 6
  • 47
  • 67
  • Thank you! I tried but somehow in my browser console, it keeps output other date after running the new Date(string) line. – user21 May 08 '18 at 11:39
  • @user21 -- Oh! I completely missed out that you can use MomentJS. I didn't see the post is tagged. But I see you accepted mahan's answer which already does that. So I will keep my answer as it is. :) – 31piy May 08 '18 at 11:48
2

Using momentjs just for determining whether a date falls on a weekend is a bit overkill.

You can do it reliably in vanilla JavaScript in just four easy steps :

  1. Split your yyyy-mm-dd into a [yyyy, mm, dd] array.
  2. Use new Date(year, month, day) to create a Date object, using the values in your array.
    Note that for month a value between 0 and 11 rather than between 1 and 12 is expected.
  3. Use date.getDay() to get a numeric representation of the day of the week, where 0 is Sunday, 1 is Monday, 2 is Tuesday, etc.
  4. Check whether the the day of the week is 0 or 6.

Demo

function isWeekend(dateString) {
  /* Step 1 */ var dateArray = dateString.split("-");
  /* Step 2 */ var date = new Date(dateArray[0], dateArray[1] - 1, dateArray[2]);
  /* Step 3 */ var day = date.getDay();
  /* Step 4 */ return day === 0 || day === 6;
}

console.log(isWeekend("2018-05-03")) // false
console.log(isWeekend("2018-05-04")) // false
console.log(isWeekend("2018-05-05")) // true
console.log(isWeekend("2018-05-06")) // true
console.log(isWeekend("2018-05-07")) // false
console.log(isWeekend("2018-05-08")) // false
Community
  • 1
  • 1
John Slegers
  • 45,213
  • 22
  • 199
  • 169
1

In momentjs, use moment('YYYY-MM-DD').day() to get the number of the day and then check if it equals 6 or 0(Saturday or Sunday).

function isWeekend(date) {
  var date = moment(date),day = date.day();
  return (day === 6) || (day === 0)
}

console.log(isWeekend("2018-05-06")) // true
console.log(isWeekend("2018-05-08")) // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
mahan
  • 12,366
  • 5
  • 48
  • 83