php - 如何在 PHP 中使用时间跨度?

标签 php mysql datetime time timespan

我有 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 之间的时间跨度?

最佳答案

PHP time() :

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

MySQL datetime :

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/

相关文章:

MySQL 子字符串搜索(前缀 ID)

datetime - iCAL DTSTART 和 DTEND 格式混淆。应该很容易回答

php - date() 方法, "A non well formed numeric value encountered"不想格式化 $_POST 中传递的日期

php - 使用 PHP 访问 Windows 共享

php - 显示过去 24 小时内的访问次数,按小时分割

java - 如何单独检索时间字段?

python-3.x - 如何在Pandas中一次将多列数据类型格式转换为另一种数据类型格式,而又不提及列名称?

php - 将时间范围合并到一个时间范围php

PHP 和 PDO 准备的语句 - 未找到列

PHP PDO 准备更新语句