Parsing a Time String with JavaScript
Categories: JavaScript
Tags: Algorithms
Let’s say you are building a UI where you’d like a user to enter a time into a text box. This time value they might enter needs to handle a lot of different formats, but we’d like it to end up as the same value either way:
- 1pm
- 1:00pm
- 1:00p
- 13:00
Here’s a little JavaScript function to do this work. Most of the interesting bits are the regular expression which helps handle of these various scenarios. It takes a string representation of a time and attempts to parse it, setting the time on the specified date object sent to the function as the second parameter. In the case where you do not provide a second parameter, the current date will be used.
function parseTime(timeStr, dt) { if (!dt) { dt = new Date(); } var time = timeStr.match(/(\d+)(?::(\d\d))?\s*(p?)/i); if (!time) { return NaN; } var hours = parseInt(time[1], 10); if (hours == 12 && !time[3]) { hours = 0; } else { hours += (hours < 12 && time[3]) ? 12 : 0; } dt.setHours(hours); dt.setMinutes(parseInt(time[2], 10) || 0); dt.setSeconds(0, 0); return dt; }
This function will return NaN if it can’t parse the input at all. The logic immediately following the match() call is to handle the noon/midnight case correctly.
Here’s a jsFiddle of this in action: