2

I have a code which stores the startdate toUTCString and endate toUTCString in a table. When I debug the code in console javascript is showing some strange behaviour.

The output in console

 var startdate = new Date($("#smdatestart").val()).toUTCString();
 var enddate = new Date($("#smdateend").val()).toUTCString();
 var now = new Date();
 var currUTCDate = now.toUTCString();//current datetime
startdate //starting date
"Mon, 02 Dec 2013 07:30:00 GMT" //in UTC
currUTCDate // current date
"Mon, 02 Dec 2013 07:15:16 GMT"  //in UTC
enddate // ending date
"Sun, 01 Dec 2013 18:30:00 GMT" //in UTC


currUTCDate > enddate //should be true but showing false
false
startdate > enddate //should be true but showing false
false
startdate > currUTCDate // this output is correct
true
Furquan Khan
  • 1,586
  • 1
  • 15
  • 30

3 Answers3

1
var startdate = new Date('Mon, 02 Dec 2013 07:30:00 GMT');
var enddate = new Date('Sun, 01 Dec 2013 18:30:00 GMT');
var currUTCDate = new Date('Mon, 02 Dec 2013 07:15:16 GMT');

startdate > enddate // true

currUTCDate > enddate // true

Anything involving '=' should use the '+' prefix. It will then compare the dates millisecond values.

+startdate  <= +currUTCDate ;  => true
+startdate >= +currUTCDate ;  => true
+startdate === +currUTCDate ; => true
Prateek
  • 6,785
  • 2
  • 24
  • 37
0

I would recommend you for first comparing dates in date format. And if condition satisfies, convert the data to utcstring and store them according to your need.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

When using == or != or > or < if the types of the two expressions are different it will attempt to convert them to string, number, or Boolean etc
use below code to compare

if ( Date.parse ( currentdate) > Date.parse ( enddate) ) {
    // your code
}
Indranil.Bharambe
  • 1,462
  • 3
  • 14
  • 25