new Date(milliseconds) returns Invalid date

随声附和 提交于 2019-11-30 03:07:10

You're not using a number, you're using a string that looks like a number. According to MDN, when you pass a string into Date, it expects

a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).

An example of such a string is "December 17, 1995 03:24:00", but you're passing in a string that looks like "1372439683000", which is not able to be parsed.

Convert Milliseconds to a number using parseInt, or a unary +:

new Date(+Milliseconds); 
new Date(parseInt(Milliseconds,10)); 

The Date function is case-sensitive:

new Date(Milliseconds); 

instead of this

new date(Milliseconds); 

use this

new Date(Milliseconds); 

your statement will give you date is not defined error

I was getting this error due to a different reason.

I read a key from redis whose value is a json.

client.get(someid, function(error, somevalue){});

Now i was trying to access the fields inside somevalue (which is a string), like somevalue.start_time, without parsing to JSON object. This was returning "undefined" which if passed to Date constructor, new Date(somevalue.start_time) returns "Invalid date".

So first using JSON.parse(somevalue) to get JSON object before accessing fields inside the json solved the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!