I have written a helper function to attempt to parse a time string in a flexible way. Sometimes the time comes in as a full date but sometimes its just a string like "10:30" or "12:01 PM".
So I am checking to see if I can parse the date first:
let date = new Date(value);
if (!isNaN(date.getTime()) // its a valid date
If that fails then I fall back to regex to check if I can make any sense of the string manually:
const isValidTime = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?(\s?(AM|PM))?$/i.test(value);
While writing unit tests I found some weird results. Incorrect times were returning actual dates in stead of throwing an error. Javascript new Date()
is parsing some of the strings and seemingly making up dates for them but also strangely, its getting the hour right too. Here are some examples of time strings that are causing this:
new Date("1:60") // Fri Jan 01 1960 01:00:00 GMT+0200
new Date("2:70") // Thu Jan 01 1970 02:00:00 GMT+0200
new Date("3:80 PM") // Tue Jan 01 1980 15:00:00 GMT+0200
//and a "valid" time for good measure
new Date("5:30") // Invalid Date
What the heck is going on here?