问题
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?
回答1:
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());
回答2:
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;
}
来源:https://stackoverflow.com/questions/1443815/round-date-to-nearest-15-minute-interval-in-flex