我从MYSQL获取日期时间,如下所示:
2010-08-11 11:18:28
我需要将其转换为“floor”或最早的15分钟间隔,并以毫秒为单位输出另一个函数。
所以,这种情况将是:
2010-08-11 11:15:00 in milliseconds
糟糕!对不起 - 需要澄清 - 我需要的代码可以将其转换为毫秒内的PHP!
进行时间测试显示以下内容:
$time_start = microtime(true);
for($i=0;$i<10000;$i++)
floor(strtotime('2010-08-11 23:59:59')/(60*15))*60*15*1000;
$time_end = microtime(true);
echo 'time taken = '.($time_end - $time_start);
所用时间= 21.440743207932
$time_start = microtime(true);
for($i=0;$i<10000;$i++)
strtotime('2010-08-11 23:59:59')-(strtotime('2010-08-11 23:59:59') % 900);
$time_end = microtime(true);
echo 'time taken = '.($time_end - $time_start);
所用时间= 39.597450017929
$time_start = microtime(true);
for($i=0;$i<10000;$i++)
bcmul((strtotime('2010-08-11 23:59:59')-(strtotime('2010-08-11 23:59:59') % 900)), 1000);
$time_end = microtime(true);
echo 'time taken = '.($time_end - $time_start);
所用时间= 42.297260046005
$time_start = microtime(true);
for($i=0;$i<10000;$i++)
floor(strtotime('2010-08-11 23:59:59')/(900))*900000;
$time_end = microtime(true);
echo 'time taken = '.($time_end - $time_start);
所用时间= 20.687357902527
所用时间= 19.32729101181
所用时间= 19.938629150391
似乎strtotime()函数是一个很慢的函数,我们可能应该避免每次需要它时使用它。 timetaken(60 * 15)!= timetaken(900)有点令人惊讶......
答案 0 :(得分:1)
以下内容将为您提供最早的15分钟间隔:
select UNIX_TIMESTAMP(YOURDATETIME)-MOD(UNIX_TIMESTAMP(YOURDATETIME), 900)
from YOURTABLE
结果是在纪元秒(自1970-01-01 00:00:00'UTC以来的秒数),如果你想要以毫秒为单位的值,你应该乘以1000(在查询中或在PHP中,就像你一样看得合适。)
修改强>
在PHP中为您的值集合:
$values = array('2010-08-11 11:18:28', '2010-08-11 11:28:28', '2010-08-11 00:00:00', '2010-08-11 23:59:59');
foreach($values as $value) {
$result = (strtotime($value)-(strtotime($value) % 900));
echo "$value -> $result\n";
}
当你将$ result乘以1000(得到以ms为单位的值)时,你可能会得到溢出,结果将被转换为float。这可能不是您想要的,因此您最好使用bcmul:
$result = bcmul((strtotime($value)-(strtotime($value) % 900)), 1000);
答案 1 :(得分:1)
这会有用吗?是不是有一些功能可以更好地做到这一点?
echo floor(strtotime('2010-08-11 11:18:28')/(60*15))*60*15*1000;
1281505500000
Wednesday, August 11, 2010 11:15:00 AM
echo floor(strtotime('2010-08-11 11:28:28')/(60*15))*60*15*1000;
1281505500000
Wednesday, August 11, 2010 11:15:00 AM
echo floor(strtotime('2010-08-11 00:00:00')/(60*15))*60*15*1000;
1281465000000
Wednesday, August 11, 2010 12:00:00 AM
echo floor(strtotime('2010-08-11 23:59:59')/(60*15))*60*15*1000;
1281550500000
Wednesday, August 11, 2010 11:45:00 PM
答案 2 :(得分:0)
尝试一下,看看会发生什么:
select DATE(myColumn)
+ CONVERT(HOUR(myColumn),CHAR(2)) + ':'
+ CASE
WHEN MINUTE(myColumn) < 15 THEN '00'
WHEN MINUTE(myColumn) < 30 THEN '15'
WHEN MINUTE(myColumn) < 45 THEN '30'
ELSE '45'
END
+ ':00' as myDate
答案 3 :(得分:0)
好的,让我们看看最糟糕的解决方案:
<?php
$ts = explode(' ', '2010-08-11 11:18:28');
$date = explode('-', $ts[0]);
$time = explode(':', $ts[1]);
$ts = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
$floor = mktime($time[0], round($time[1]/15)*15, 0, $date[1], $date[2], $date[0]);