What is the best way to analyze a time in a Date object since the user entered Javascript?


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.

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

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:

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