Skip to content

Instantly share code, notes, and snippets.

@larzconwell
Created May 18, 2012 15:22
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 larzconwell/2725837 to your computer and use it in GitHub Desktop.
Save larzconwell/2725837 to your computer and use it in GitHub Desktop.
convert_format = function(time) {
var hour = Number(time.replace(/:[0-9]+/, '').replace(/ *[a-z]+/, ''))
, min = Number(time.replace(/[0-9]+:/, '').replace(/ *[a-z]+/, ''))
, ampm = time.replace(/[0-9]+:/, '').replace(/[0-9]+ */, '');
if(ampm !== '') {
// Convert to 24 hour time(Removing ampm)
// Time: 0:00 - 23:59
if(hour === 12 && ampm === 'am') hour = 0;
if(ampm === 'pm' && hour < 12) {
hour += 12;
}
if(hour > 23) hour = 0;
time = hour + ':' + min;
} else {
// Convert to 12 hour time(No ampm previously)
// Time: 12:00-11:59AM - 12:00-11:59PM
if(hour < 11) ampm = 'am';
if(hour >= 12) ampm = 'pm';
if(hour === 0) {
hour = 12;
ampm = 'am';
}
if(hour > 12) hour -= 12;
time = hour + ':' + min + ' ' + ampm;
}
return time;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment