最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript convert date string to date - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Aug 18, 2011 at 19:19 mustapha georgemustapha george 6215 gold badges13 silver badges17 bronze badges 3
  • 5 sigh Man, no one puts out any effort to just search for answers. This type of question has been answered over and over here and many other places on the web. – Jonathan M Commented Aug 18, 2011 at 19:24
  • 2 geez. I just checked and noticed that everything has been answered at least once on the web, so let's close this board down because it adds nothing to the community. Even better, lets keep it going and just tell people to RTFM and just refer them to google. – mustapha george Commented Aug 19, 2011 at 22:20
  • Effort is appreciated here. It will get better answers. Strange, but true. :) – Jonathan M Commented Aug 20, 2011 at 18:00
Add a comment  | 

5 Answers 5

Reset to default 13

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!

发布评论

评论列表(0)

  1. 暂无评论