Thanks to Derek of Subtitle Designs, who pointed out this "neato" script to me (for the second time!), I got curious as to what is involved in hacking the script to work with time instead of dates.
How it works (in 10 easy steps (or less) ;))
- User-entered value is passed to
parseTimeString()to parse that string and to return a
parseTimeString()loops through an array of objects, each having a regular expression, trying to match the entered text.
- Once a regexp match is found, a corresponding function is called to "translate" the match to a valid
- The result
Dateis passed back to
magicTime(), which calls the callback function
getReadable()for any tweaking and formatting of the result before displaying it (default output is hh:mm:ss)
Improvements of the original idea
Apart from just processing time instead of dates, there are a few improvements to the original script.
- Regexps examples and (unit?) testing. In the array of objects where the regexp rules are defines, I've added another property - an array of examples illustrating sample matches. The purpose is two fold - to quickly provide a help with a list of supported formats and also to have the ability to test the regexps semi-automatically. So then the function
getExamples()is called, it produces a list of acceptable values. If the same function is called passing a TRUE parameter, these example values are actually parsed and the result of the parsing is returned. This allows to quickly test all the regexps. Click "help" and/or "run tests!" in the demo for an illustration.
getReadable()- a function that formats the output is introduced, allowing the users of this script to customize it quickly without interfering with the main logic. In this function you can opt for dropping the seconds, or rounding to the next minute, or five minutes, or an hour, or anything that has to do with displaying the result of the successful parse.
- Optional message area. The message area, placed under the text box is optional. There is now a
try..catchto make sure no JS error occurs if it's missing.
How to use the script
It shouldn't be a problem to integrate this into your application. You need to:
- (optionally) Tweak
getReadable()to match your needs. Remember that at this time all parsing work is done and you have a valid Date object which you only need to display to the user
- (optionally) Place a div to display messages, related to the text box (see the demo). Name it with id
magicTime()when you think appropriate (like
onblur), passing the input element (e.g.
document.getElementById('id-of-the-input'), or just
this, depending from where you call it)
Any comments, bug reports or requests are welcome! Thanks!