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

查看:26
本文介绍了如何从 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
  • 下午 1:00
  • 下午 1:00
  • 下午 1:00
  • 下午 1:00
  • 1:00p
  • 下午 1 点
  • 下午 1 点
  • 1 个人
  • 下午 1 点
  • 下午 1 点
  • 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+)(?::(dd))?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]) );
}

它也应该适用于其他一些品种(即使使用了 a.m.,它仍然可以工作 - 例如).显然这很粗糙,但它也很轻量级(例如,使用它比使用完整库便宜得多).

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天全站免登陆