Comparison dates don't get work in angular js

Can someone tell me why my date is not working. Basically, when I try to compare the date, then it does not work 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 works, but for the case below does not work, if I use the date as "26-Apr-2016", I will 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; } 
+5
source share
2 answers

According to the documentation of the date filter, this filter

Formats a date into a string based on the requested format.

So, when comparing dateObj1 with dateObj2, you use string comparison, which is a lexicographic order.

You should Date.parse your string before the date (using Date.parse ) to get the desired results.

+2
source

Note This Date.parse is required to complete 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> 
+1
source

All Articles