JavaScript date() 对象使用 getYear(和其他)返回 NaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7610886/
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
JavaScript date() Object returns NaN with getYear (and other)
提问by Rene Pot
I am currently having some issues converting a string dateTime object in JavaScript
我目前在 JavaScript 中转换字符串 dateTime 对象时遇到一些问题
I am assuming it is because my string cannot me used properly in a new Date()
but I'm not sure that is the problem.
我假设这是因为我的字符串不能在 a 中正确使用,new Date()
但我不确定这是问题所在。
My Input: "2011-09-29 14:58:12"
我的输入:“2011-09-29 14:58:12”
My code:
我的代码:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year
var contains NaN. Same with getDay() or getMonth(). What is the problem?
但是,我的year
var 包含 NaN。与 getDay() 或 getMonth() 相同。问题是什么?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
ps:我从 SQLite 数据库中以它的格式获取日期。而且我使用的是 Titanium Mobile,所以 javascript 和 SQLite 是唯一涉及的东西
回答by T.J. Crowder
You're relying on the Date
constuctorparsing an unsupported format. Until recently, there was nostandard string format supported by the Date
constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS
, note the T
rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
您依赖于解析不受支持的格式的Date
构造函数。直到最近,构造函数都不支持标准的字符串格式Date
。从 ECMAScript5 开始,有一个 ( YYYY-MM-DDTHH:MM:SS
,请注意T
而不是空格),但它只被指定了不到两年的时间,自然在旧浏览器中不起作用。
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJSto parse it for you (and provide lots of other useful date/time stuff).
目前,最好的办法是自己解析它(您可以在这个问题及其答案中找到代码),或者使用DateJS 之类的东西为您解析它(并提供许多其他有用的日期/时间内容)。
回答by Bryan Kyle
The Date
constructor will not parse a string for you. You'll need to use Date.parse
to do that. Interestingly enough, Date.parse
doesn't actually return a Date
. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date
constructor to get what you're looking for.
该Date
构造不会解析字符串为您服务。你需要使用它Date.parse
来做到这一点。有趣的是,Date.parse
实际上并没有返回Date
. 相反,它返回一个 unix 时间戳。然后,您可以将 unix 时间戳传递到Date
构造函数中以获取您要查找的内容。
var d = new Date(Date.parse("2011-09-29 14:58:12"));