Skip to content

Instantly share code, notes, and snippets.

@hugowetterberg
Created June 9, 2009 14:41
Show Gist options
  • Save hugowetterberg/126551 to your computer and use it in GitHub Desktop.
Save hugowetterberg/126551 to your computer and use it in GitHub Desktop.
Time format interpreter
(function(){
var tsplit = /[^\d]/, pad_time = function (time) {
if (time<10 && time.length<2) {
return '0' + time.toString();
}
else {
return time;
}
},
normalize_time = function (inp) {
var ts = jQuery(inp).val(), ta = ts.split(tsplit), h=0, m=0;
if (ta.length == 1) {
switch (ts.length) {
case 1:
h = ts;
break;
case 2:
if (ts<24) {
h = ts;
}
else {
h = ts.substr(0, 1);
m = ts.substr(1, 1);
if (m<6) {
m *= 10;
}
}
break;
case 3:
h = ts.substr(0, 1);
m = ts.substr(1, 2);
break;
case 4:
h = ts.substr(0, 2);
m = ts.substr(2, 2);
break;
}
}
else {
h = ta[0];
m = ta[1];
if (m<6) {
m *= 10;
}
}
if (m>59) {
h = parseInt(h, 10) + (m - m%60) / 60;
m = m%60;
}
jQuery(inp).val(pad_time(h) + ':' + pad_time(m));
if (jQuery(inp).val().length < 5 && m==0) {
jQuery(inp).val(jQuery(inp).val() + '0');
}
};
jQuery('#starts_time, #ends_time').change(function() {
normalize_time(this);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment