Jimothy
Jimothy

Reputation: 87

Javascript Date Comparison Strange Behavior

I have a function that computes a start date and an end date.

It then prints out this code:

   $log.log("currentDate: " + currentDate);
   $log.log("currentDate: " + startDate + " " + (currentDate.valueOf() > startDate.valueOf()));
   $log.log("currentDate: " + endDate + " " + (currentDate.valueOf() < endDate.valueOf()));

But in my console window, the comparisons return false, even when they should return true!

currentDate: Fri Mar 18 2016 14:09:26 GMT-0500 (CDT)angular.js:12722 
currentDate: Fri Mar 18 2016 08:00:26 GMT-0500 (CDT) false
currentDate: Fri Mar 18 2016 19:30:26 GMT-0500 (CDT) false

Am I doing something wrong here?

Upvotes: 0

Views: 53

Answers (1)

mario ruiz
mario ruiz

Reputation: 1000

I don't have the complete context about your variables but I created a plunker and works as expected using only setTimeout. Please check how valueOf() is working as expected and giving true

var currentDate, endDate, startDate= new Date();

setTimeout(function(){
  currentDate = new Date();
}, 1000)
setTimeout(function(){
  endDate = new Date();
},2000)

setTimeout(function(){
  $log.log("currentDate: " + currentDate);
  $log.log("currentDate: " + startDate + " " + (currentDate.valueOf() > startDate.valueOf()));
  $log.log("currentDate: " + endDate + " " + (currentDate.valueOf() < endDate.valueOf()));
  $scope.message = 'Hello World!';
},3000);

Upvotes: 1

Related Questions