AngularJs ng-if comparing dates

All we need is an easy explanation of the problem, so here it is.

I am looking to compare two dates in ng-if this is what my jade file looks like.

li.list-group-item(ng-if="app.Segments[0].StartDate.getTime() > date.getTime()")
    div.row
        div.col-xs-12
            span
                i.fa.fa-plus-square

This code will hopefully add an li to my ui if the startdate of the first segment is after today.

$scope.date = new Date();
$scope.app = {
    Segments: [{
       StartDate: 2014-11-15T04:00:00.000Z
       EndDate: 2014-11-20T04:00:00.000Z
    },
    {
        StartDate: 2014-11-21T04:00:00.000Z
        EndDate: 2014-11-25T04:00:00.000Z
    }]

}

Is there anyway to make this work?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If they’re date object just compare them directly without .getTime()

$scope.date2005 = new Date('2005/01/01');
$scope.date2006 = new Date('2006-01-01T04:00:00.000Z');
<div ng-if="date2005 > date2006">date2005 > date2006</div> <!-- won't show -->
<div ng-if="date2006 > date2005">date2006 > date2005</div> <!-- will show -->

http://plnkr.co/edit/fNB11U6KmFszdV3lMAPJ?p=preview

Method 2

Angular can directly compare date if they are well formated:

view

li.list-group-item(ng-if="app.Segments[0].StartDate > now")

controller

$scope.now = new Date();
$scope.now.toISOString();

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply