php - 查找当前时间并减去以前的时间(以秒为单位)
问题描述
我正在尝试查找当前日期和时间,转换为 unix 时间戳,然后减去以前的时间。我尝试了多种方法并收到错误或不正确的值。到目前为止,这是我的代码:
// Current date and time
$currentTime = date("Y-m-d H:i:s");
// Convert datetime to Unix timestamp
$currentTimestamp = strtotime($currentTime);
// Create previous date and time
$previousTime = new DateTime("2021-04-17 13:00:00");
// Specify display format
$previousTime->format('Y-m-d H:i:s');
// Convert to Unix timestamp
$previousTimestamp = strtotime($previousTime);
// Subtract previous time from current time
$time = $currentTimestamp - $previousTimestamp;
// Display result
echo $time;
那么它应该如何工作,如果当前日期和时间是例如:2021-04-17 14:00:00 而之前的日期和时间是 2021-04-17 13:00:00,那么结果应该是 3600 .或者如果有两个小时的间隔,那么它是7200,等等。使用这个当前代码,我得到的错误是:
Uncaught TypeError: strtotime(): Argument #1 ($datetime) must be of type string, DateTime
我尝试过的其他代码没有返回正确的时差或引发其他错误。如何获得正确的时差?
解决方案
您需要阅读有关每个函数期望作为参数以及每个函数返回什么的文档。您正在将时间戳(整数)与 DateTime 对象混合。如果要进行日期计算,则需要对两者使用相同的格式。由于您正在寻找秒数差异,因此使用时间戳整数可能更简单。
此代码为您提供一个整数时间戳:
$currentTime = date("Y-m-d H:i:s");
$currentTimestamp = strtotime($currentTime);
但请注意,“now”是time()
函数的默认返回值,因此您可以这样做:
$currentTimestamp = time();
你不需要这个:
// This gives you a DateTime object
$previousTime = new DateTime("2021-04-17 13:00:00");
// This doesn't change the internal representation,
// it just returns a value that you're not using.
$previousTime->format('Y-m-d H:i:s');
// This function expects a string, but you're giving an object.
$previousTimestamp = strtotime($previousTime);
相反,您可以直接将格式化的日期字符串传递给strtotime()
它,它将返回一个整数时间戳:
$previousTimestamp = strtotime("2021-04-17 13:00:00");
现在你有两个代表秒数的整数,所以你可以把它们相减以获得它们之间的秒数。你的编成:
$currentTimestamp = time();
$previousTimestamp = strtotime("2021-04-17 13:00:00");
$diff = $currentTimestamp - $previousTimestamp;
echo $diff;
要不就:
echo time() - strtotime("2021-04-17 13:00:00");
推荐阅读
- django - 如何在 Django REST API 的序列化程序中使用 2 个模型?
- android-management-api - API_LEVEL 不合规细节……有什么要担心的吗?
- javascript - 获取完整的 url 表单服务器
- python - 根据熊猫中的条件返回列名列表作为新列
- pandas - 如何选择熊猫数据框中特定列中一系列值之间的所有行
- sql - 如何排除oracle sql组中的小时,分钟,秒
- sql - 获取具有性别男性和女性的姓名
- c# - 如何添加自定义声明类型
- z3 - z3中实际值计算的问题
- database - Jmeter脚本开发:IBM cloudant性能测试,最大请求/秒