Dates comparing not get work in angular js

匿名 (未验证) 提交于 2019-12-03 00:52:01

问题:

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;     } 

回答1:

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



回答2:

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>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!