javascriptangularjsscopemomentjsweekend

Determine whether a date falls on weekend in Angular/Javascript


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("");
  /* } */
}

Solution

  • 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