如何通过JavaScript中的用户输入将时间解析为Date对象? [英] How to parse a time into a Date object from user input in JavaScript?

查看:85
本文介绍了如何通过JavaScript中的用户输入将时间解析为Date对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个表单小部件,以便用户将一天中的某个时间输入到文本输入中(对于日历应用程序)。使用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()对象:

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

  • 1pm

  • 下午1点

  • 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?

推荐答案

一种适用于您指定的输入的快速解决方案:

A quick solution which works on the input that you've specified:

function parseTime( t ) {
   var d = new Date();
   var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ );
   d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) );
   d.setMinutes( parseInt( time[2]) || 0 );
   return d;
}

var tests = [
  '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', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', 
  '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
  '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];

for ( var i = 0; i < tests.length; i++ ) {
  console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}

它也应适用于其他几个品种(即使使用了am,它仍然可以使用-例如)。显然,这很粗糙,但也很轻巧(例如,比使用完整的库便宜得多)。

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


警告:该代码不适用于上午12:00,依此类推。

Warning: The code doe not work with 12:00 AM, etc.

这篇关于如何通过JavaScript中的用户输入将时间解析为Date对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆