Reputation: 121
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;
}
Upvotes: 5
Views: 465
Reputation: 2246
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
Upvotes: 2
Reputation: 5273
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>
Upvotes: 1