简体   繁体   English

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

[英]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? 是否有更原生的方式来存储日期在JavaScript中?

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. 它的工作原理。

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

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

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

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. Date.parse(您的日期字符串)返回自1970年1月1日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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM