5

Can anyone tell me why my date is not get working. Basically when i try to compare date then is is not working in angularJs

  var dateObj1 = $filter("date")(Date.now(), 'dd-MMM-yyyy'); // output is "04-May-2016"
    var dateObj2 = $scope.employee.Tue; // output is "03-May-2016"
    if (dateObj1 < dateObj2) {         
        return true
    } else {
        return false;
    }

above is working but for case below is not working if i use date as "26-Apr-2016" i get true in return

 var dateObj1 = $filter("date")(Date.now(), 'dd-MMM-yyyy'); // output is "04-May-2016"
    var dateObj2 = $scope.employee.Tue; // output is "26-Apr-2016"
    if (dateObj1 < dateObj2) {         
        return true
    } else {
        return false;
    }
3
  • 1
    you are checking dateObj instead of dateObj1 Commented May 4, 2016 at 8:02
  • i change the above code but still same issue Commented May 4, 2016 at 8:03
  • What type is dateObj2? Even when the output looks like a date, it could be a string. Commented May 4, 2016 at 8:07

2 Answers 2

2

According to the documentation of the date filter, this filter

Formats date to a string based on the requested format.

So when comparing dateObj1 to dateObj2, you are using the string comparison which is the lexicographic order.

You must parse your string to a Date (by using Date.parse) to obtains the wanted results

Sign up to request clarification or add additional context in comments.

Comments

1

Check out This, Date.parse is needed to accomplish this task

var jimApp = angular.module("mainApp",  []);

jimApp.controller('mainCtrl', function($scope, $filter){
  var dateObj1 = $filter("date")(Date.now(), 'dd-MMM-yyyy'); // output is "04-May-2016"
  var dateObj2 = Date.parse("26-Apr-2016");
  if (Date.parse(dateObj1) < dateObj2) {
    alert(true);
    return true
  }
  else {
    alert(false);
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.