Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

datetime - JavaScript date() Object returns NaN with getYear (and other)

I am currently having some issues converting a string dateTime object in JavaScript

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.

My Input: "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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard 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.

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 DateJS, MomentJS, date-fns, etc. to parse it for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...