I have the following code in my controller
:
$scope.a="26-04-2016";
$scope.c = moment($scope.a,"DD-MM-YYYY").format("DD-MM-YYYY");
$scope.b="20-10-2016";
$scope.d = moment($scope.b,"DD-MM-YYYY").format("DD-MM-YYYY");
if($scope.d <= $scope.c){
alert($scope.d+' es menor a '+$scope.c)
}else{
alert($scope.d+' es mayor a '+$scope.c)
}
With this I compare two dates between the 20-10-2016
and the 26-04-2016
, at first glance it is known that the 20-10-2016
is greater than 26-04-2016
but when executing this code it gives me the result that it is less.
What is the problem?
The problem is this:
This is redundant and it is also the reason that you are comparing dates as strings, not as
Date
javascript objects and when you compare strings they will give you more or less according to a comparison algorithm that follows different steps (step 4) as if both operands of the algorithm were dates (step 3).So the possible solutions can be
Don't dispose of the
moment
original object and use it to do the comparisons using the methods (recommended)isSame
(===
)isBefore
(<
)isAfter
(>
)isSameOrBefore
(<=
)isSameOrAfter
(>=
)Here is an example
moment
toDate
and compare using the corresponding methodsFinally I recommend that you manipulate your dates using the ISO 8601 format . This is not mandatory but it is the standard and it will save you from having to do a lot of date format conversions in your programs.
You can also compare them as JSON, i.e.:
Just yesterday I tried it with AngularJS (Angular 1) and it worked :)
.format() converts the date (the moment object) to a text string. If you use the standard format, sorting by year, month, day would not be a problem. But you are indicating that the output format is day, month, year, so when comparing the text strings it will treat them as numbers, not as dates, so 26042016 is greater than 20102016.
The solution is to compare the moment objects directly, or with the moment comparison functions: isBefore() and isAfter(). Then the format is given at the time of displaying the variable.
I can't test it but I think this will work for you