Furquan Khan
Furquan Khan

Reputation: 1594

Javascript datetime issue

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

Upvotes: 2

Views: 205

Answers (3)

Indranil.Bharambe
Indranil.Bharambe

Reputation: 1498

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
}

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82251

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.

Upvotes: 0

Prateek
Prateek

Reputation: 6975

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

Upvotes: 1

Related Questions