简体   繁体   English

如何将日期字符串转换为Date对象?

[英]How to convert a date string to a Date object?

How to convert a date string to a Date object? 如何将日期字符串转换为Date对象?

An example date string: 日期字符串示例:

31.12.2009 23:12:00
var parts = "31.12.2009 23:12:00".match(/\d+/g);
new Date(parts[2], parts[1]-1, parts[0], parts[3], parts[4], parts[5]);

Parse it and create it. 解析并创建它。

Note : Month is zero based. 注意 :月是从零开始的。

I recommend the Date.js library . 我建议使用Date.js库

It can handle all kinds of date parsing and converting, and other date related functionality. 它可以处理各种日期解析和转换以及其他与日期相关的功能。 Very handy for this kind of thing. 这种事情非常方便。

hope that helps. 希望能有所帮助。

JavaScript by default parses date strings with the ISO 8601 format, which is... JavaScript默认情况下使用ISO 8601格式解析日期字符串,即...

YYYY-MM-DDTHH:mm:ss.sssZ YYYY-MM-DDTHH:MM:ss.sssZ

If you can get your datetime in this format it would probably be best. 如果您可以使用这种格式获取日期时间,那将是最好的选择。 You do not want to run into any culture issues. 您不想遇到任何文化问题。 In JavaScript you can do it with toISOString() . 在JavaScript中,您可以使用toISOString()来实现 If you can't do this, you'll have to parse out the date yourself or use a library. 如果无法执行此操作,则必须自己解析日期或使用库。

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

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