Javascript javascript将日期字符串转换为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7112901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:53:47  来源:igfitidea点击:

javascript convert date string to date

javascriptdate

提问by mustapha george

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?

有没有更原生的方式来在 javascript 中存储日期?

回答by Joe

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

我已经在 IE7、IE8、IE9、chrome 和 firefox 6 中测试过这个:

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

and it works.

它有效。

回答by Jake Kalstad

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

http://www.w3schools.com/jsref/jsref_obj_date.asp提供了一些见解,只需将其打包并发送,您就会发现提供的各种便利。

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

回答by trnelson

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. :)

也许不是最好的方法,但如果您的地址是标准化的,它可能不会太糟糕,并且实施/执行可能会很快。:)

回答by James

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:

Date.parse(your date string) 返回自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。存储此号码。如果要显示日期,请使用 new Date(theNumber)。例子:

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)

回答by dr4g0nus

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

Date 对象非常方便,因此您可以直接在新对象中使用该字符串。

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

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!

我说了很多,但是当涉及到这样的事情时,在浏览器控制台中进行实验并真正了解对象能够做什么总是很棒的......快乐编码!