javascript 新日期(毫秒)返回无效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17371302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:04:13  来源:igfitidea点击:

new Date(milliseconds) returns Invalid date

javascriptdatetimemilliseconds

提问by user1634451

I am trying to convert milliseconds to a date using the javascript using:

我正在尝试使用 javascript 将毫秒转换为日期:

new Date(Milliseconds); 

constructor, but when I give it a milliseconds value of say 1372439683000 it returns invalid date. If I go to a site that converts milliseconds to dateit returns the correct date.

构造函数,但是当我给它一个毫秒值说 1372439683000 它返回无效日期。如果我访问一个将毫秒转换为日期站点,它会返回正确的日期。

Any ideas why?

任何想法为什么?

回答by apsillers

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

您不是在使用数字,而是在使用看起来像数字的字符串。根据 MDN,当您将字符串传递给 时Date,它期望

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

解析方法识别的格式(符合 IETF 的 RFC 2822 时间戳)。

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.

此类字符串的一个示例是“ December 17, 1995 03:24:00”,但您传入的字符串看起来像“ 1372439683000”,无法解析。

Convert Millisecondsto a number using parseInt, or a unary +:

Milliseconds使用parseInt或一元转换为数字+

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

回答by ic3b3rg

The Datefunction is case-sensitive:

Date函数区分大小写:

new Date(Milliseconds); 

回答by Sachin

instead of this

而不是这个

new date(Milliseconds); 

use this

用这个

new Date(Milliseconds); 

your statement will give you date is not definederror

你的陈述会给你日期未定义错误

回答by Vinay Vemula

I was getting this error due to a different reason.

由于不同的原因,我收到此错误。

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

我从 redis 中读取了一个键,它的值是一个 json。

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

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".

现在我试图访问里面的字段somevalue(这是一个字符串),比如somevalue.start_time,而不解析为 JSON 对象。这是返回“未定义”,如果传递给日期构造函数,则new Date(somevalue.start_time)返回“无效日期”。

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

所以JSON.parse(somevalue)在访问json内部的字段之前首先使用获取JSON对象解决了这个问题。