user756659
user756659

Reputation: 3512

Why does the Date class return NaN?

Getting strange results when converting a timestamp to readable date.

var date = new Date(x);

console.log(x);

showTooltip(item.pageX, item.pageY, (date.getMonth()+1)+"-"+date.getDate()+"-"+date.getFullYear()+" / "+y );

The console shows for example '1404792000000' so the timestamp is good, but the output results in 'NaN-NaN-NaN / 864'.

What am I doing wrong here?

Upvotes: 0

Views: 1270

Answers (2)

user2226755
user2226755

Reputation: 13223

Verify x with typeof function like this :

console.log(typeof x);

X must to be an number (int) if is an timestamp (like this 1404792000000), use parseInt() function if x is a string.

var date = new Date(parseInt(x));

showTooltip(item.pageX, item.pageY, (date.getMonth()+1)+"-"+date.getDate()+"-"+date.getFullYear()+" / "+y );

Example :

date = new Date("1404792000000"); // String : Date {Invalid Date}

date = new Date(1404792000000); // Integer : Date {Tue Jul 08 2014 ...}

date = new Date(parseInt("1404792000000")); // Str to int : Date {Tue Jul 08 2014 ...}

Without parseInt, use the calculator operator. (@RobG comment)

Like this :

date = new Date(+"1404792000000"); // Str to int

Which is better to use for a calculator parseInt() or eval() in Javascript?

Upvotes: 3

user2864740
user2864740

Reputation: 61985

The reason is that new Date('1404792000000') results in an "Invalid Date" object, so all the access methods (e.g. getMonth) return NaN. This is because the date constructor does not accept a string representing the epoch milliseconds.

Compare with new Date(1404792000000), which is "Mon Jul 07 2014 21:00:00 GMT-0700 (Pacific Daylight Time)". Note how a number was specified.

Upvotes: 1

Related Questions