Skip to content

Instantly share code, notes, and snippets.

@jessegavin
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessegavin/34465cdd7102bdeaf4de to your computer and use it in GitHub Desktop.
Save jessegavin/34465cdd7102bdeaf4de to your computer and use it in GitHub Desktop.
Time Parsing
function parseHoursAndMinutes(input) {
if (typeof input !== "string") {
throw "Time must be a string";
}
input = input.toLowerCase().trim();
if (input.length === 0) {
throw "Time must not be empty";
}
var hours = 0;
var minutes = "00";
var parts = input.split(":");
hours = parseInt(parts[0],10);
if (isNaN(hours)) {
throw "Cannot parse '"+ input +"'";
}
if (hours < 0) {
throw "Hours must be greater than zero";
}
if (hours > 23) {
throw "There are not that many hours in a day";
}
if (hours <= 12 && /pm?$/i.test(input)) {
hours += 12;
}
if (parts.length > 1) {
minutes = parseInt(parts[1],10);
if (isNaN(minutes)) {
minutes = 0;
}
if (minutes > 59) {
throw "There are only 60 minutes in an hour";
}
if (minutes < 0) {
throw "Minutes must be greater than zero";
}
}
return {
hours: hours,
minutes: minutes
};
}
var cases = [
"1p", "00:59", "23:14", "5:30",
"11:59 pm", "12AM", "11a", "notatime"
];
cases.forEach(function(item) {
var result;
var d;
try {
// parse it
result = parseHoursAndMinutes(item);
// Create a new moment and set hours and minutes
d = moment().hours(result.hours).minutes(result.minutes);
// print it
console.log(d.format("h:mm a"));
} catch(err) {
console.error(err);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment