Assuming I have a unix timestamp in PHP. How can I round my php timestamp to the nearest minute? E.g. 16:45:00 as opposed to 16:45:34?
Thanks for your help! :)
2. You also can use this formula =MROUND(A2,15/60/24) to round time to nearest minute. 3. If you want to round time to previous 15 minute, use this formula =FLOOR(A2,15/60/24).
Round time to nearest hour ( TIME(1,0,0) = 1/24 representing an hour) and add a zero time value to ensure the expression is cast as a Time. M: There isn't an equivalent of MROUND in M, so instead multiply the time by 24 to express it as a number of hours, then round, then divide by 24 and convert to a Time type.
To round the DateTimeIndex with minute frequency, use the DateTimeIndex. round() method. For minute frequency, use the freq parameter with value 'T'.
If the timestamp is a Unix style timestamp, simply
$rounded = round($time/60)*60;
If it is the style you indicated, you can simply convert it to a Unix style timestamp and back
$rounded = date('H:i:s', round(strtotime('16:45:34')/60)*60);
round()
is used as a simple way of ensuring it rounds to x
for values between x - 0.5 <= x < x + 0.5
. If you always wanted to always round down (like indicated) you could use floor()
or the modulo function
$rounded = floor($time/60)*60; //or $rounded = time() - time() % 60;
An alternative is this:
$t = time(); $t -= $t % 60; echo $t;
I've read that each call to time()
in PHP had to go all the way through the stack back to the OS. I don't know if this has been changed in 5.3+ or not? The above code reduces the calls to time()...
Benchmark code:
$ php -r '$s = microtime(TRUE); for ($i = 0; $i < 10000000; $i++); $t = time(); $t -= $t %60; $e = microtime(TRUE); echo $e - $s . "\n\n";' $ php -r '$s = microtime(TRUE); for ($i = 0; $i < 10000000; $i++); $t = time() - time() % 60; $e = microtime(TRUE); echo $e - $s . "\n\n";' $ php -r '$s = microtime(TRUE); for ($i = 0; $i < 10000000; $i++); $t = floor(time() / 60) * 60; $e = microtime(TRUE); echo $e - $s . "\n\n";'
Interestingly, over 10,000,000 itterations all three actually do the same time ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With