0

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.

3
  • You know "2016-10-18".split('-').reverse().join(',') becomes "18,10,2016" which isn't any kind of date format Commented Oct 19, 2016 at 10:07
  • new Date('2016-10-18') seems to create the correct Date instance just fine. Not sure at all what you're trying to achieve Commented Oct 19, 2016 at 10:10
  • @Phil : But while i am taking date like 2016-10-06 this ,its working fine. Commented Oct 19, 2016 at 10:13

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

@ Satpal : Its showing alert even input is todays date also i.e-2016-10-19 which should not come.
@subhra, Time is also considered, new Date() will consider current date and time where as new Date('2016-10-18') will set date with timezone offset
So in this case how can i do this. Here only input is date.
@ Satpal : Can you take date value as 2016-10-19 and check ?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.