ThomasReggi
ThomasReggi

Reputation: 59555

Timestamp Inconsistency

I was playing around with JavaScript dates and I'm looking for an explanation pertaining to the last logged array. Why are the numbers 1352589000, 1352589395 different?

Code

var examples = [
    "Fri Jan 16 1970 10:43:09 GMT-0500 (EST)",
    1352589395
];

var text = [
    new Date((examples[0])),
    new Date((examples[1])),
];

var unix = [
    new Date((examples[0])).getTime(),
    new Date((examples[1])).getTime(),
];

console.log(examples);
console.log(text);
console.log(unix);

Output

[
  'Fri Jan 16 1970 10:43:09 GMT-0500 (EST)',
  1352589395
][
  'Fri Jan 16 1970 10:43:09 GMT-0500 (EST)' ,
  'Fri Jan 16 1970 10:43:09 GMT-0500 (EST)' 
][
  1352589000,
  1352589395
]

Upvotes: 4

Views: 222

Answers (3)

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17305

You are giving two different times to Date() and both of them are incorrect. Javascript's Date object accepts no argument for current time or milliseconds or date string or [year, month, day, hours, minutes, seconds, milliseconds].

"Fri Jan 16 1970 10:43:09 GMT-0500 (EST)" is invalid format for Date(). For correct DateString formats check https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/parse

Upvotes: -1

Tim Withers
Tim Withers

Reputation: 12069

Because that Unix time stamp is in milliseconds. You didn't specify milliseconds, so it is giving you exactly 10:43:09 on Jan 16, 1970. The other time stamp is giving you 10:43:09.395 on Jan 16, 1970.

EDIT

The Unix timestamp is the number of SECONDS since the Jan 1st, 1970. Javascript's getTime() returns the number of MILLISECONDS since Jan 1st, 1970. So yes it is the Unix timestamp... in milliseconds.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075597

The numbers are in milliseconds. The difference between them is 395, which is less than half a second. The string format you're using only goes down to the second, and so its milliseconds portion is 0, but the number you're parsing includes the milliseconds (all 395 of them).

Upvotes: 1

Related Questions