Format a number to time like hh:mm
format, formatting, javascript, jquery
Solution
You can do this with some simple regex:
function time( str ) {
if ( !/:/.test( str ) ) { str += ':00'; }
return str.replace(/^\d{1}:/, '0$&').replace(/:\d{1}$/, '$&0' );
}
If you want to make sure only the expected format is accepted, add this line at the top of the function:
if ( /[^:\d]/.test( str ) ) { return false; }
Demo: http://jsfiddle.net/elclanrs/MzgMz/
Problem
I have an iput field: ``` <input type="text" name="time" class="time" value="3" /> ``` I need that value to be like 03:00 More examples of what I need: ``` 1 = 01:00 12 = 12:00 12:2 = 12:20 2:2 = 02:20 02:2 = 02:20 340 = 340:00 340:1 = 340:10 ``` You know the rest. How can I solve this in jquery/javascript? This is what I try in jQuery: ``` $('input').blur(timeFormat); function timeFormat(e){ skjema.find('input.tid').each(function(){ if($(this).val().length != 0){ var tid = $(this).val().toString(); if(tid.length == 1){ $(this).val(String("0" + tid)); } if(tid.indexOf(':') == -1){ $(this).val(tid.toString() + ':00'); } } }); } ``` This is what I have made now and it does the job, but it is somewhat bulky :) ``` function timeFormat(e){ skjema.find('input.tid').each(function(){ if($(this).val().length != 0){ var tid = $(this).val().toString(); tid = (tid.length == 1) ? '0' + tid : tid; tid = (tid.indexOf(':') == -1) ? tid + ':00' : tid; if(tid.indexOf(':') != -1){ var arr = tid.split(':'); var before = arr[0].toString(); var after = arr[1].toString(); before = (before.length == 0) ? '00' : before; before = (before.length == 1) ? '0' + before : before; after = (after.length == 0) ? '00' : after; after = (after.length == 1) ? after + '0' : after; console.log('before: ' + before + ' After: ' + after); tid = before + ':' + after; } } $(this).val(tid); }); } ```