Search code examples
javascriptangularjshtmlunix-timestamp

Change color if date is weekend using javascript


I have code to check weekend and recolor it.

$scope.today = data.getDate() + '/' + (data.getMonth()+1)+ '/' + data.getFullYear();
if($scope.today.getDay() == 6 || $scope.today.getDay() == 0){
    console.log($scope.today+' is Weekend');
    //change color here
    //something like
    //$scope.date.fontcolor("blue");
} 

HTML code

<td>{{today}}</td>

data is from datepicker. And got error

TypeError: $scope.today.getDay is not a function

Solution

  • First, you should use Date object.

    $scope.today = new Date();
    if($scope.today.getDay() == 6 || $scope.today.getDay() == 0){
        console.log($scope.today+' is Weekend');
    }
    

    Then you use Angularjs filter in your html so you can display the format that you want.

    <td>{{ today | date:'dd/MM/yyyy }}</td>
    

    Second, you can use a flag to check if it is today.

    $scope.today = new Date();
    if($scope.today.getDay() == 6 || $scope.today.getDay() == 0){
        console.log($scope.today+' is Weekend');
        $scope.isWeekend = true;
    }
    else {
        $scope.isWeekend = false;
    }
    

    Then you use this flag to control a class for coloring your font using ng-class.

    <td ng-class="{'weekend': isWeekend}">{{ today | date:'dd/MM/yyyy }}</td>
    

    To finish it, you create a CSS for "weekend" class to set the font color as you desire.

    .weekend {
        color: blue;
    }