从Javascript的用户输入中将Date转换成Date对象的最佳方式是什么? [英] What is the best way to parse a time into a Date object from user input in Javascript?
问题描述
我正在使用表单窗口小部件,用户可以输入文本输入(日历应用程序)中的时间。使用JavaScript(我们正在使用jQuery FWIW),我想找到解析用户输入到JavaScript Date()
对象的文本的最佳方式,以便我可以轻松执行
I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript Date()
object so I can easily perform comparisons and other things on it.
我尝试了 parse()
方法,它有点太挑剔了我的需要我希望它能够成功地解析以下示例输入时间(除了其他逻辑上类似的时间格式),因为相同的 Date()
object:
I tried the parse()
method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same Date()
object:
- 1:00 pm
- 1:00 pm
- 1: 00 p
- 1:00 pm
- 1:00 p.m。
- 1:00p
- 1 pm
- 1 pm
- 1 p
-
- 1 p.m。
- 1p
- 13:00
- 13
- 1:00 pm
- 1:00 p.m.
- 1:00 p
- 1:00pm
- 1:00p.m.
- 1:00p
- 1 pm
- 1 p.m.
- 1 p
- 1pm
- 1p.m.
- 1p
- 13:00
- 13
我想我可以使用正则表达式来分割输入,并提取我想用来创建我的 Date()
对象。什么是最好的方法?
I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my Date()
object. What is the best way to do this?
推荐答案
一个快速的解决方案,适用于您指定的输入: p>
A quick solution which works on the input that you've specified:
var times = ['1:00 pm','1:00 p.m.','1:00 p','1:00pm',
'1:00p.m.','1:00p','1 pm','1 p.m.','1 p','1pm','1p.m.', '1p','13:00','13'];
for ( var i = 0; i < times.length; i++ ) {
var d = new Date();
var time = times[i].match(/(\d+)(?::(\d\d))?\s*(p?)/);
d.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
d.setMinutes( parseInt(time[2]) || 0 );
console.log( d );
}
它也适用于其他几个品种(即使使用了,它仍然可以工作 - 例如)。显然这是非常粗糙的,但它也是非常轻便的(比使用完整的图书馆便宜得多)。
It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example).
这篇关于从Javascript的用户输入中将Date转换成Date对象的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!