简体   繁体   English

无法使用Angular.js / Javascript比较日期

[英]Can not compare date using Angular.js/Javascript

I have an issue. 我有一个问题。 I can not compare todays date with previous date using Angular.js/Javascript. 我无法使用Angular.js / Javascript将今天的日期与以前的日期进行比较。 I am explaining my code below. 我在下面解释我的代码。

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

Here i am getting $scope.date1 value like this 2016-10-18 format.Here i could not compare while date is 2016-10-18 .Here i need while selected date is previous date of todays date that alert will display.Please help me. 在这里,我正在获得$scope.date1值,例如2016-10-18格式。在这里,我无法比较日期为2016-10-18日期。在这里,我需要在选定日期是警报将显示的今天日期的前一个日期。帮我。

new Date($scope.date1.split("-").reverse().join(",")) will not create a valid date. 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'); } 

You cannot compare dates as you are doing. 您无法在执行操作时比较日期。

When you initialize date object with new Date() , it is set with current time. 当您使用new Date()初始化日期对象时,它会设置为当前时间。

So 所以

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

shall never be the same 永远不会一样

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

The above expression evaluates to true because if you see the time of both the dates 上面的表达式计算为true,因为如果同时看到两个日期的时间

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

To compare it on the basis of only date you need to set time of anothertoday to 0 by anothertoday.setHours(0,0,0,0) 要仅根据date进行比较,您需要将anothertoday时间设置为0 by anothertoday.setHours(0,0,0,0)

Now the above expression should evaluate to false 现在上面的表达式应该计算为false

anothertoday > today //---->false

So in your case your code should be similar to this 因此,在您的情况下,您的代码应与此类似

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM