2

I am trying to use gettime to sort my date string. But it is returning some vague values like.

  1. 1428303000000 16/06/2014 16:50
  2. 1389074040000 01/07/2014 16:54

The first date is smaller than second so its no. of milliseconds should also be smaller.

You can also check it on http://www.tutorialspoint.com/cgi-binpractice.cgi?file=javascript_178

So don't know why this is behaving like this.

Any help ?

Arun
  • 23
  • 3
  • Yes, the link is not working. Try using JSFiddle. – fakedad Jul 14 '14 at 02:16
  • Are you are doing something like `new Date('16/06/2014 16:50')`? Because `new Date(1428303000000)` is sometime about 6 April, 2015. – RobG Jul 14 '14 at 02:30
  • The link where i was testing is http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=javascript_178 – Arun Jul 14 '14 at 03:34

2 Answers2

2

You're probably creating the date using 16/06/2014 and intending this to mean the 16th day of the 6th month. However, this is not how it's parsed. The first element is treated as the month; the second element is the day. Since there aren't 16 months in a year, the date is rounded forward to the next year (i.e. the 16th month of 2014 is the 4th month of 2015).

In other words:

Date.parse("16/06/2014 16:50") === Date.parse("04/06/2015 16:50"); // => true
Wayne
  • 59,728
  • 15
  • 131
  • 126
  • Bottom line: **don't use Date.parse**. The OP is ending up with an implementation dependent result (if browsers think that is the 16th month, they should probably return NaN since it's an invalid date). – RobG Jul 14 '14 at 02:32
  • Well, certainly don't give it dates in unsupported formats. – Wayne Jul 14 '14 at 02:34
  • The problem is that there is one standardised format for use with *Date.parse* and it's not what the OP is using, nor is it supported consistently by all browsers in use. Some don't support the standardised format at all. :-( – RobG Jul 14 '14 at 02:36
  • You're definitely right about implementation-specific behavior, though. For example, Firefox's behavior is explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse – Wayne Jul 14 '14 at 02:36
2

Test your code if you are correctly creating Date object

// new Date(year, month, day, hour, minute, second, millisecond);

// Working with date 16/06/2014 16:50
var foo = new Date(2014, 6, 16, 16, 50);
foo.getTime(); // 1405518600000

// Working with date 01/07/2014 16:54 
var foo = new Date(2014, 7, 1, 16, 54);
foo.getTime(); // 1406901240000

Read more about Date object reference.

Until we see your code and how do you get from "16/06/2014 16:50" to "1428303000000", I can't help more.

Deele
  • 3,728
  • 2
  • 33
  • 51
  • I tested this like – Arun Jul 14 '14 at 03:36
  • Yes, it doesn't work like that. I'm glad I helped you understand your mistake by yourself. – Deele Jul 14 '14 at 03:49