tags:

views:

674

answers:

3

I am building a control to allow me to set a meeting time, and I would like it to use as a default, the current time rounded up to the nearest 15 minute interval. So if it is currently 6:07, it would read 6:15 as the start time.

Does anyone know how this might be accomplished, or have run across a code snippit that would put me on the right track?

+2  A: 

Try this

var date:Date = new Date();
var min:Number = date.minutes;
var h:Number = date.hours;
min = min + (15 - min % 15);
h += min / 60;
min = min % 60;
date.hours = h;
date.minutes = min;
trace(date.toTimeString());
Amarghosh
Thanks! That works very well. I went ahead and modified it slightly to the following, which allows me to specify the interval:protected function roundTimeToInterval( date:Date, interval:int ):Date{ var min:Number = date.minutes; var h:Number = date.hours; min = min + (interval - min % interval); h += min / 60; min = min % 60; date.hours = h; date.minutes = min; return date;}
Nick
A: 

Thanks! That works very well. I went ahead and modified it slightly to the following, which allows me to specify the interval:

protected function roundTimeToInterval( date:Date, interval:int ):Date
{
 var min:Number = date.minutes;
 var h:Number = date.hours;
 min = min + (interval - min % interval);
 h += min / 60;
 min = min % 60;
 date.hours = h;
 date.minutes = min;

 return date;
}
Nick
+1  A: 

I found that with the Amarghosh's answer is it doesn't quite round correctly. Example: it rounds 7:01 to be 7:15, not 7:00. It also wouldn't handle changing in dates (example rounding 23:50 to the next day), etc.

This will do what you want, while handling changing days, months and years even, and the math's a bit simpler:

protected function roundTimeToMinutes( date:Date, interval:int ):Date
{
    var time:Number=date.getTime();
    var roundNumerator=60000*interval; //there are 60000 milliseconds in a minute
    var newTime:Number=( Math.round( time / roundNumerator ) * roundNumerator );
    date.setTime(newTime);
    return date;
}
Martamius
Awesome answer! Haven't I seen you on wow somewhere?
Byron Whitlock