« [News] SLUG meeting was held at Space Airconditioning, UK on 13 July 05 and started at 4:15 p.m. | Main | [Tip] The trick for the use of returns in calculations used in an RTF_AREA »
July 28, 2005
[Tip] A Calculation to round off time into quarters
by Robert Ivens
www.roclasi.com
Someone on the Servoy forum came with a question about how to round off time into quarters. Another person even suggested this could be done in a one-liner. Lets take a look at this.
To round minutes into whole quarters you can divide the minutes by 15 and then round that to whole numbers and multiply it by 15 again to get minutes again.
var min = 36;
min = Math.round(min/15)*15
--> 30
But when you have 55 minutes it rounds up to 0 (zero). So that means you have to add another hour then. Same issue occurs when you use a date time value of 23:55. Now you not only have to add an hour, but also a day.
That would be a lot of IF THEN ELSE's to just round some time up to whole quarters. There has to be a smarter way to do this....
This is what I came up with:
var dt = new Date(); // get the current date time value
dt = new Date(Math.round(dt/1000/60/15)*15*60*1000);
Let me explain this one-liner:
A Date has in fact a value in milliseconds (1/1000 of a second) counting from Jan 01, 1970 01:00:00 CET. So adding or subtracting milliseconds to it takes care of any hour or day changes when calculating with time.
So what the one-liner does is this:
datetime_in_milliseconds divided by 1000 to make seconds,
divided by 60 to make minutes,
divided by 15 to make the quarters of an hour.
Round that to whole numbers.
And now back to milliseconds again:
result_of_rounding multiplied by 15 to make minutes,
multiplied by 60 to make seconds,
multiplied by 1000 to make milliseconds.
Now put that large number inside a Date() object and you get a nice rounded datetime value.
| Posted by Robert Ivens on July 28, 2005 at 12:15 AM in Tips | Permalink