PHP将时间舍入到最接近的15秒 [英] PHP round the time to the nearest 15 seconds

查看:105
本文介绍了PHP将时间舍入到最接近的15秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个重复的问题,但是对时间有一点了解.

This is not a duplicate question, but involves a little understanding about time.

我需要解决以下问题 我有一些专门制作的时间(基于日期),需要四舍五入到最接近的15秒:

I need a solution to the following problem I have a number of specifically produced times (based on a date), that need to be rounded to the nearest 15 secs:

60秒是1分钟 表示常规的圆,底,上限是最接近的小数点(10/5) 这没有时间帮助我. 同样由于我要处理秒数,因此59:59可能会四舍五入到最接近的小时数: 17:59:59应该是18:00.

60 secs is 1 minute meaning a regular round, floor, ceiling is to the nearest decimal (10/5) which doesn't help me with time. also since I'm dealing with secs, it could be that 59:59 will be rounded up to the nearest hour: e.g. 17:59:59 should be 18:00.

示例:

6:17:29舍入到6:17:30 6:29:55舍入到6:30:00 20:45:34舍入到20:45:30

6:17:29 rounded to 6:17:30 6:29:55 rounded to 6:30:00 20:45:34 rounded to 20:45:30

以下代码完成了一些工作:

The following code does some of the job:

$hr = date('H',($resultStr));
$mn = date('i',($resultStr));
$sc = date('s',($resultStr));

$tot = ($hr * 60 * 60) + ($mn * 60) + $sc;
$totd = $tot / (60);
$totc = ceil($totd);
$totc = $totc / 60;
$hr = floor($totc);
$mn = ($totc - $hr)*60;
$mnflr = floor($mn);
$mn2 = $mn - $mnflr;
echo "$hr:$mnflr";

这导致: 18:35:17取整为:18:36(这是错误的) 18:31:49舍入为:18:32(这是错误的)

This results in: 18:35:17 rounded to: 18:36 (which is wrong) 18:31:49 rounded to: 18:32 (which is wrong)

顺便说一句:

$secs = date('U',($resultStr));
$round = ceil ( (($secs / 60 ) * 60 ));
$newtime = date('H:i:s',($round));

产生:18:42:58舍入为:18:42:58这也是不正确的

produces: 18:42:58 rounded to: 18:42:58 which is also incorrect

请先谢谢你....

推荐答案

您正在使这个过程过于复杂,只需在Unix时间戳级别进行四舍五入即可.

You're massively overcomplicating this, just do rounding on the Unix timestamp level:

function roundMyTime($time)
{
  $time = strtotime($time);
  $time = 15*round($time/15);
  echo date('H:i:s', $time)."\n";
}
roundMyTime('18:35:17');
roundMyTime('18:35:27');
roundMyTime('18:35:37');
roundMyTime('18:35:47');
roundMyTime('18:35:57');
roundMyTime('18:36:07');
roundMyTime('18:36:17');

输出:

18:35:15
18:35:30
18:35:30
18:35:45
18:36:00
18:36:00
18:36:15

在此处演示.

这篇关于PHP将时间舍入到最接近的15秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆