不能使用Angular.js/Javascript比较日期

Can not compare date using Angular.js/Javascript

本文关键字:Javascript 比较 日期 js Angular 不能      更新时间:2023-09-26

我有一个问题。我不能用Angular.js/Javascript比较今天的日期和以前的日期。我在下面解释我的代码。

 var today=new Date();
 if(today >= new Date($scope.date1.split("-").reverse().join(","))){
    alert('Please select todays date or upcoming date');
 }

这里我得到$scope.date1值像这个2016-10-18格式。在这里,我无法比较,而日期是2016-10-18。在这里,我需要,而选择的日期是今天的日期之前的日期,警报将显示。

new Date($scope.date1.split("-").reverse().join(","))将不会创建有效的日期。

//Pass the string directly
var nDate = new Date('2016-10-18'); 
var today = new Date();
if (today >= nDate) {
  console.log('Please select todays date or upcoming date');
}

你不能像现在这样比较日期。

当你用new Date()初始化date对象时,它被设置为当前时间。

var today = new Date("2016-10-19"); //----> current date here
var anothertoday = new Date();

不应该是相同的

anothertoday > today //-----> true

上面的表达式求值为true,因为如果您看到两个日期

的时间
today.getHours() //---> 0
anothertoday.getHours() //---> current time shall be displayed

要在仅date的基础上进行比较,需要通过anothertoday.setHours(0,0,0,0)anothertoday的时间设置为0

现在上面的表达式应该求值为false

anothertoday > today //---->false

在你的例子中你的代码应该类似于这个

var today = new Date();
$scope.date1 = "2016-10-18";
$scope.datearr = $scope.date1.split("-");
var yesterday = new Date($scope.datearr[0],$scope.datearr[1] - 1,$scope.datearr[2]);
today.setHours(0,0,0,0); //----> set time to 0 hours
if(today > yesterday)
   console.log("Please select todays date or upcoming date");