Compare dates with momentsjs in angularjs

1

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 we know that the 20-10-2016 is greater than the 26-04-2016 but when executing this code it gives me as a result that it is smaller.

What is the problem?

    
asked by Dimoreno 20.10.2016 в 08:32
source

4 answers

-1

I can not prove it but I think this will work for you

$scope.a="26-04-2016";    
$scope.c = moment($scope.a,"DD-MM-YYYY").format("YYYY-MM-DD");
$scope.b="20-10-2016";
$scope.d = moment($scope.b,"DD-MM-YYYY").format("YYYY-MM-DD");
if($scope.d <= $scope.c){
    alert($scope.d+' es menor a '+$scope.c)
}else{
    alert($scope.d+' es mayor a '+$scope.c)
}
    
answered by 20.10.2016 / 11:17
source
0

You can also compare them as JSON, that is:

if($scope.d.toJSON() <= $scope.d.toJSON())

Yesterday I tried it with Angular and it worked:)

    
answered by 20.10.2016 в 13:35
0

.format () converts the date (the moment object) to a text string. If you use the standard format, when ordered by year, month, day, there would be no 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 dates, so 26042016 is larger than 20102016.

The solution is to compare the moment objects directly, or with the moment comparison functions: isBefore () and isAfter (). Then the format you give it at the time of showing the variable.

$scope.a="26-04-2016";    
$scope.c = moment($scope.a,"DD-MM-YYYY");
$scope.b="20-10-2016";
$scope.d = moment($scope.b,"DD-MM-YYYY");
if($scope.d <= $scope.c){
    alert($scope.d.format("YYYY-MM-DD") + ' es menor a  '+ $scope.c.format("YYYY-MM-DD"))
}else{
    alert($scope.d.format("YYYY-MM-DD") + ' es mayor a ' + $scope.c.format("YYYY-MM-DD"))
}
    
answered by 20.10.2016 в 15:49
0

The problem is this:

// Creas un String con la fecha
$scope.a="26-04-2016"; 

$scope.c = 
    // Creas un objeto moment a partir de ese String
    moment($scope.a,"DD-MM-YYYY")

    // Vuelves a convertir dicho objeto moment a String
    // que es exactamente igual a $scope.a
    .format("DD-MM-YYYY");

    // String --> moment --> String

This is redundant and it is also the cause that you are comparing the dates as strings of characters, not as objects Date of javascript and when you compare chains these will give you more or less according to a comparison algorithm that follows different steps (step 4) that if both operands of the algorithm were dates (step 3).

var $scope = {};

$scope.a = "26-04-2016";
$scope.b = "20-10-2016";

$scope.a1 = new Date('2016-04-26');
$scope.b1 = new Date('2016-10-20');

//$scope.a >= $scope.b => true
console.log('$scope.a >= $scope.b :', $scope.a >= $scope.b);
// "26" >= "20" => true
console.log('"26" >= "20" :', "26" >= "20");
//$scope.a1 >= $scope.b1 => false
console.log('$scope.a1 >= $scope.b1 :', $scope.a1 >= $scope.b1);

So the possible solutions can be

  • Do not discard the original%% of the original% object and use this to make the comparisons using the methods (recommended)

    moment ( isSame )

    === ( isBefore )

    < ( isAfter )

    > ( isSameOrBefore )

    <= ( isSameOrAfter )

    Here is an example

  • angular.module('app', [])
      .controller('DateCtrl', function($scope) {
    
        $scope.a = "26-04-2016";
        $scope.c = moment($scope.a, "DD-MM-YYYY");
        $scope.b = "20-10-2016";
        $scope.d = moment($scope.b, "DD-MM-YYYY");
    
        if ($scope.d.isSameOrBefore($scope.c)) {
          alert($scope.b + ' es menor a ' + $scope.a)
        } else {
          alert($scope.b + ' es mayor a ' + $scope.a)
        }
    
      });
    <script src="http://momentjs.com/downloads/moment.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="DateCtrl">
      {{a}}
      <br>{{b}}
    </div>
  • Convert the >= to moment and compare using the corresponding methods
  • angular.module('app', [])
      .controller('DateCtrl', function($scope) {
        // Tambien puedes descomponer las fechas y crear el objeto Date directamente
        $scope.a = "26-04-2016";
        $scope.c = moment($scope.a, "DD-MM-YYYY").toDate();
        $scope.b = "20-10-2016";
        $scope.d = moment($scope.b, "DD-MM-YYYY").toDate();
    
        if ($scope.d <= $scope.c) {
          alert($scope.b + ' es menor a ' + $scope.a)
        } else {
          alert($scope.b + ' es mayor a ' + $scope.a)
        }
    
      });
    <script src="http://momentjs.com/downloads/moment.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="DateCtrl">
      {{a}}
      <br>{{b}}
    </div>

    Finally I recommend that you manipulate your dates using the format ISO 8601 . This is not mandatory but it is the standard and this will save you having to do many date format conversions in your programs.

        
    answered by 20.10.2016 в 19:10