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("");
/* } */
}
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 :
yyyy-mm-dd
into a [yyyy, mm, dd]
array.new Date(year, month, day)
to create a Date
object, using the values in your array.month
a value between 0 and 11 rather than between 1 and 12 is expected.date.getDay()
to get a numeric representation of the day of the week, where 0 is Sunday, 1 is Monday, 2 is Tuesday, etc.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