简体   繁体   English

来自Javascript中包含非数字字符的字符串的数字数组

[英]Numeric array from string containing non-numeric characters in Javascript

I have a bunch of dates in some .xml files in this format : 2013-02-10 12:00 (year, month, day, hour, minutes) and I want to create a Date object from it. 我在这些格式的一些.xml文件中有一堆日期: 2013-02-10 12:00 (年,月,日,小时,分钟),我想从中创建一个Date对象。

I did new Date(stringFromXml) in Chrome and it works, but it doesn't work in Firefox/IE. 我在Chrome中使用了new Date(stringFromXml)并且它可以工作,但它在Firefox / IE中不起作用。

What I wanted to do is split that string in a 5 element array and create a Date object manually with the constructor that accepts a year, month, day, etc. The thing is that I couldn't make it work with regular expressions and .split isn't the most elegant solution. 我想要做的是将该字符串拆分为5个元素数组,并使用接受年,月,日等的构造函数手动创建Date对象。事情是我无法使用正则表达式和.split不是最优雅的解决方案。

I already know about date.js but I don't want to add another library to my project. 我已经知道date.js但我不想在我的项目中添加另一个库。

What should I do to make this work? 我应该怎么做才能使这项工作? Also, I am using jQuery 另外,我正在使用jQuery

试试Date.parse

var date = Date.parse(" date string here ");

这应该让你走上正确的道路......

var dateParts = date.split(/(-| |:)/);

If the format is always the same, you can hack it together like this: 如果格式始终相同,您可以像这样一起破解它:

var parts = '2013-02-10 12:00'.split(/[: -]/);
var d = new Date(
    parts[0] /* year */, parts[1] /* month */, parts[2] /* day */, 
    parts[3] /* hour */, parts[4] /* minute */
);

If you already have the Datepicker widget, you can use the parseDate() function from the date picker extension: 如果你已经有了Datepicker控件,您可以使用parseDate()从日期选取器扩展功能:

var date = $.datepicker.parseDate('yy-mm-dd hh:mm', '2013-02-10 12:00');

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

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