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 开发者_JS百科to store dates in javascript?
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.
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);
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. :)
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)
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!
精彩评论