【问题标题】:Basic PHP Time calculation having a wrong answer基本的 PHP 时间计算有错误的答案
【发布时间】:2020-11-15 20:55:21
【问题描述】:

我有这个基本的 PHP 时间计算,它只是在两个时间戳之间减去,但它会额外返回一个小时。

echo date('h:i:s',strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00'));

我希望答案是 55 分钟 (00:55:00) 相反,它给出了 01:55:00

编辑:在 PHP fiddle 上它工作正常,在我的服务器上它没有(并且时间设置正确)

有什么见解吗?

【问题讨论】:

标签: php


【解决方案1】:

通过 date_create() 函数创建日期对象

$date1 = date_create("y-m-d H:i:s");

$date2 = date_create("y-m-d H:i:s");

print_r(date_diff($date1-$date2));

你可以得到年、月、小时、分钟、秒的差异

【讨论】:

  • 此代码包含语法错误,date_diff 错误。另外,我的问题不是有替代方案,而是要了解为什么它给了我错误的答案。感谢您的努力
  • date_diff 内置获取时差函数
  • 你也会得到错误 类 DateTime 的对象无法转换为 int ,使用 date_diff($date1,$date2) 它将返回数组
  • 感谢大家的帮助。干杯
【解决方案2】:

试试这个。解释和输出见 cmets。

<?php

$from = '2020-11-15 11:05:00';
$to = '2020-11-15 12:00:00';

// 'U' gets UNIX seconds since epoch.
$fromSeconds = (new DateTime($from))->format('U');
$toSeconds = (new DateTime($to))->format('U');
$interval = $toSeconds - $fromSeconds;

// Get number of days
$days = floor($interval / 86400);
$interval -= $days * 86400;
// Get number of hours
$hours = floor($interval / 3600);
$interval -= $hours * 3600;
// Get number of minutes
$minutes = floor($interval / 60);
$interval -= $hours * 60; 

var_dump($days); // 0
var_dump($hours); // 0
var_dump($minutes); // 55

这解释了您第一次尝试时发生的情况:

$seconds = strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00');
var_dump($seconds); // 3300

// You're passing an _interval_ to date(), where it expects a timestamp
// in UNIX epoch format.
// Which means, seconds counted from UNIX time 0.
// UNIX time 0 starts at 1970-01-01 01:00:00!
// See:
echo date('Y-m-d H:i:s', 0); // 1970-01-01 01:00:00!

// Your code is formatting the TIME, not the INTERVAL of your argument.
// Which is the 1 from 01:00:00 and 55 minutes from your value.

【讨论】:

  • 有道理...我的时区也有问题,这使问题进一步复杂化。干杯,被选为答案。
  • 很高兴我能提供帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2012-08-11
相关资源
最近更新 更多