Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 230
Rene Pot Avatar asked Sep 30 '11 13:09

Rene Pot


People also ask

What does the Date object return in JavaScript?

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

How does JavaScript store dates in Adate object?

JavaScript Stores Dates as Milliseconds JavaScript stores dates as number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated). Zero time is January 01, 1970 00:00:00 UTC.

Which JavaScript object works with the dates?

The Date Object. The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data.

What is Date now () in JavaScript?

The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


1 Answers

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.

like image 93
T.J. Crowder Avatar answered Nov 07 '22 21:11

T.J. Crowder