【问题标题】:Find Current Time and Subtract Previous Time in Seconds查找当前时间并减去以前的时间(以秒为单位)
【发布时间】:2021-07-12 12:39:51
【问题描述】:

我正在尝试查找当前日期和时间,转换为 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 输入字符串,日期时间

我尝试过的其他代码没有返回正确的时差或引发其他错误。如何获得正确的时差?

【问题讨论】:

  • 为什么不用DateTime的sub()方法呢?

标签: php datetime timestamp


【解决方案1】:

您需要阅读有关每个函数期望作为参数以及每个函数返回什么的文档。您正在将时间戳(整数)与 DateTime 对象混合。如果要进行日期计算,则需要对两者使用相同的格式。由于您正在寻找秒数差异,因此使用时间戳整数可能更简单。

这段代码给你一个整数时间戳:

$currentTime = date("Y-m-d H:i:s");
$currentTimestamp = strtotime($currentTime);

但请注意,“现在”是 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");

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 2018-05-22
    • 2010-10-02
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    相关资源
    最近更新 更多