3

We've found in our code the next line (yes, you can ask why it even exists, but it does):

console.log(new Date(2015, 10, 9).toString() > new Date(2015, 9, 10).toString())
// Returns false

console.log(new Date(2015, 5, 9).toString() > new Date(2015, 4, 10).toString())
// Returns true

We don't understand how it works exactly, so hopefully someone can explain.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
Mario
  • 582
  • 5
  • 18

4 Answers4

3

toString returns string representation of date in the following format

new Date(2015, 10, 9).toString();

"Mon Nov 09 2015 00:00:00 GMT+0530 (India Standard Time)"

First line

console.log(new Date(2015, 10, 9).toString() > new Date(2015, 9, 10).toString())

is false because M > S is false

Second line

console.log(new Date(2015, 5, 9).toString() > new Date(2015, 4, 10).toString())

is true because T > M is true

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

I did this on node, see the output, it should be self-explaintory

> console.log(new Date(2015, 10, 9).toString())
Mon Nov 09 2015 00:00:00 GMT+0800 (+08)

> console.log( new Date(2015, 4, 10).toString())
Sun May 10 2015 00:00:00 GMT+0800 (+08)

> console.log(new Date(2015, 5, 9).toString())
Tue Jun 09 2015 00:00:00 GMT+0800 (+08)

> console.log(new Date(2015, 4, 10).toString())
Sun May 10 2015 00:00:00 GMT+0800 (+08)
Umesh
  • 2,704
  • 19
  • 21
1

Basically the above expressions evaluate to:

console.log("Mon Nov 09 2015 00:00:00 GMT+0100 (CET)" > "Sat Oct 10 2015 00:00:00 GMT+0200 (CEST)");
//false

console.log("Tue Jun 09 2015 00:00:00 GMT+0200 (CEST)" > "Sun May 10 2015 00:00:00 GMT+0200 (CEST)");
//true

Now, why is that? JavaScript compares strings Lexicographically.

Meaning the first letters of each strings get compared first according to their alphabetical order.


First expression: S is later in the alphabet. Therefore its greater than M.

Second expression: T is later in the alphabet. Therefore its greater than S.

NullDev
  • 6,739
  • 4
  • 30
  • 54
0

I am not much of an expert in string manipulation, but for the first case ...

new Date(2015, 10, 9).toString()

gives the date in string depending on the region you are in, in my case, it is

Mon Nov 09 2015 00:00:00 GMT+0500 (Pakistan Standard Time)

and for new Date(2015, 9, 10).toString()

I get "Sat Oct 10 2015 00:00:00 GMT+0500 (Pakistan Standard Time)"

Now, the when a comparison is done between two string, in this case it is >, the javascript engine compares the first character of two strings, and alphabetically M comes before S, so the first console.log gives false, as M is not greater than S.

Similar explanation goes for the second case where the character T comes after S, hence T is greater than S is true.

Waleed Iqbal
  • 1,308
  • 19
  • 35