mustapha george
mustapha george

Reputation: 621

javascript convert date string to date

How do I convert a string like this back to a date object?

"Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)"

Is there a more native way to store dates in javascript?

Upvotes: 4

Views: 23679

Answers (5)

dr4g0nus
dr4g0nus

Reputation: 133

The Date object is quite accommodating so you can just use the string directly in a new object.

http://www.w3schools.com/js/js_obj_date.asp

new Date("Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)")

I say this a lot but when it comes to things like this, it's always awesome to experiment in the browser console and really get a feel for what the objects are capable of doing.. happy coding!

Upvotes: 0

James
James

Reputation: 22247

Date.parse(your date string) returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. Store this number. When you want to display a date, use new Date(theNumber). Example:

var milliseconds = Date.parse("Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)");
// milliseconds == 1313694835000


alert(new Date(milliseconds));
// alerts  Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)

Upvotes: 0

trnelson
trnelson

Reputation: 2763

If your dates will always be in a standard format (for sure), you could split into an array based on the space character and then create a date object from the items in the array.

Maybe not best approach but if your addresses are standardized, it might not be too bad, and probably pretty fast to implement/execute. :)

Upvotes: 0

Joe
Joe

Reputation: 82604

I've tested this in IE7, IE8, IE9, chrome, and firefox 6:

new Date('Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)');

and it works.

Upvotes: 13

Jake Kalstad
Jake Kalstad

Reputation: 2065

http://www.w3schools.com/jsref/jsref_obj_date.asp provides some insight, just package it up and send it through and youll find all sorts of conveniance provided.

var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Upvotes: 2

Related Questions