osomanden
osomanden

Reputation: 643

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

Upvotes: 1

Views: 83

Answers (3)

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

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');
	}
	for (var i = 0; i < str.length; i++) {
		if (str[i].length > 2) {
			str[i] = str[i].substr(0, 2);
		}
		if (str[i].length == 0) {
			str[i] = '00';
		}
	}
	//Force 0-23
	str[0] = (parseInt(str[0]) % 24).toString();
	//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')
	]);

function displayInHTML() {
	//Get value from element
	var input = (document.getElementById("time").value).toString();
	var output = document.getElementById("output");
	output.innerHTML = toTime(input);
}
<input type="text" id="time" name="time" onkeyup="displayInHTML()"/>
<textarea style="width:100%" id="output" readonly></textarea>

Upvotes: 1

zoom
zoom

Reputation: 1756

To round a number of minutes to the nearest quarter you can use:

var x = minutes + 7;
minutes = x - (x % 15)

var minutes, x;
for (minutes = 0; minutes <= 50; minutes++) {
    x = minutes + 7;
    console.log(minutes + ' : ' + (x - (x % 15)));
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386756

You can divide minutes by 15 and multiply the rounded result with 15 for the right quarter.

var minutes;

for (minutes = 0; minutes < 60; minutes++) {
    console.log(minutes + ': ' + (Math.round(minutes / 15) * 15));
}

Upvotes: 2

Related Questions