user5443928
user5443928

Reputation:

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. 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.

Upvotes: 0

Views: 41

Answers (2)

Nishant123
Nishant123

Reputation: 1966

You cannot compare dates as you are doing.

When you initialize date object with new Date(), it is set with current time.

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

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)

Now the above expression should evaluate to 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");

Upvotes: 0

Satpal
Satpal

Reputation: 133453

new Date($scope.date1.split("-").reverse().join(",")) will not create a valid date.

//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');
}

Upvotes: 1

Related Questions