我有 2 个字段要填充:页面每 15 分钟和每小时被调用的次数。
以下字段是 MySql 中的 DateTime:
$lastAccess15m=$row['lastAccess15m'];
$lastAccessHour=$row['lastAccessHour'];
这些字段是整数:
$accessPer15m=$row['accessPer15m'];
$accessPerHour=$row['accessPerHour'];
我想将当前时间与$lastAccess15
进行比较,如果时间距离大于15分钟,则将$lastAccess15
的值设置为当前时间,并重新设置$accessPer15m
,否则递增$accessPer15m
。 $lastAccessHour
和 $accessPerHour
也是如此,之后这些值必须保存到 mysql 数据库中。
如何以分钟/小时为单位获取当前时间和 $accessPer15m 之间的时间跨度?
最佳答案
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
要比较它们,您需要转换一个,然后它们执行比较:
$phpDateFromMysql = strtotime( $mysqldate );
$mySqlDateFromPHP = date('Y-m-d H:i:s', $phpdate);
最简单的方法是将 Mysql 值转换为 time() 并执行比较:
查看此 working Example !
<?php
// compare if the value from $lastAccess15 is +15min in relation to the current time
$lastAccess15 = '2012-06-01 00:00:00';
$phpDateFromMysql = strtotime( $lastAccess15 );
if ($phpDateFromMysql - $lastAccess15 > 900) {
$lastAccess15 = date('Y-m-d H:i:s', time());
}
echo $lastAccess15;
?>
注意:在 if
语句中,您可以执行剩余的操作,甚至可以添加一个 else
子句来执行一些 if 操作时间不超过 15 分钟(就像你提到的增量)。
相关阅读资料:
PHP strtotime功能
PHP date功能
PHP elseif/else if控制结构
关于php - 如何在 PHP 中使用时间跨度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11057298/