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?
This is a more rugged approach that takes into account how users intend to use this type of input. For example, if a user entered "12", they would expect it to be 12pm (noon), and not 12am. The below function handles all of this. It is also available here: http://blog.de-zwart.net/2010-02/javascript-parse-time/
This is a string prototype, so you can use it like so:
I have made some modifications to the function above to support a few more formats.
Ain't cleaned it up yet but works for everything I can think of.
The time package is 0.9kbs in size. Available with NPM and bower package managers.
Here's an example straight from the
README.md
:Why not use validation to narrow down what a user can put in and simplify the list to only include formats that can be parsed (or parsed after some tweaking).
I don't think it's asking too much to require a user to put a time in a supported format.
dd:dd A(m)/P(m)
dd A(m)/P(m)
dd
An improvement to Patrick McElhaney's solution (his does not handle 12am correctly)
Lots of answers so one more won't hurt.
To be properly robust, it should check that each value is within range of allowed values, e.g if am/pm hours must be 1 to 12 inclusive, otherwise 0 to 24 inclusive, etc.