osomanden osomanden - 4 months ago 11
Javascript Question

javascript return time to closest quarter

Having an input field with time given like hh:mm.

Any one having a function that


  1. check for correct time syntax.

  2. change to
    :
    if anything else eg.
    .,;
    is entered separating hour and minutes.

  3. format time to closest 15 min. eg. 05 -> 00, 08 -> 15.



Edit:
Input comes from this:

<input name=event_time_end id=event_time_end type=text maxlengt=5 size=5 value='' onblur='toTime(this);'>


Regards

Answer

This solution enforces syntax, removes excess characters and formats the result as a valid time:

console.clear();
function closestQuarter(n) {
	return (Math.round(n % 60 / 15) * 15) % 60;
}
function toTime(str) {
	str = str
		//Replace non-digist with ':'
		.replace(/(?:\D*)?\D+/g, ':')
		//Replace first ':' with '*' to give us a target
		.replace(':', '*')
		//Remove ':'
		.replace(/:/g, '')
		//Split by '*'
		.split('*');
	//In case of empty string
	if (str.length < 1) {
		str.push('00');
	}
	//In case of only hours
	if (str.length < 2) {
		str.push('00');
	}
	//Round to quarter
	str[1] = closestQuarter(parseInt(str[1])).toString();
	//Prepend '0' if needed
	for (var i = 0; i < str.length; i++) {
		if (str[i].length < 2) {
			str[i] = '0' + str[i];
		}
	}
	//Return a ':' joined string
	return str.join(':')
}
//Tests
console.log([toTime('21:45'),
		toTime('21:4'),
		toTime('1:3'),
		toTime('1.3'),
		toTime('1.3i3'),
		toTime('13.37pm')
	]);

Comments