PHP Diff 部分日期时间

标签 php mysql datetime

我正在尝试减去当前日期时间与我的数据库中规定的时间之间的时差。日期时间当前格式为 yyyy:mm:dd hh:mm:ss,但是对于这种特定情况,我只想减去时间而不是日期,所以我只想计算 hh:mm:ss,然后将其存储到不同的变量我可以使用和格式化我想要的。是否可以获取完整的日期时间,将其拆分并对其进行比较?我认为这有点令人困惑,所以询问您是否需要澄清。到目前为止,这是我尝试过的:

<?php
//The time in the database
$classTime = DateTime::createFromFormat('Y-m-d H:i:s', '0000-00-00 18:30:00');

$timein = new DateTime("now", new DateTimeZone('America/Detroit'));
$timein->getTimestamp();
$timeout = $classTime;
$totaltime = $timeout->diff($timein);
$totaltime = $totaltime->format('Y-m-d H:i:s');
$totaltime = date('0000:00:00 H:i:s', strtotime($totaltime));
//I create a new date because i'm storing this time into the database, which can't be done with a datetime.

//FORMAT TIMES
$timein = $timein->format('Y-m-d H:i:s');
$timeout = $timeout->format('Y-m-d H:i:s');
echo "Time in " . $timein . " Time Out " . $timeout . " Total Time " . $totaltime;
?>

当前输出返回:

Time in 2013-04-02 14:05:32 Time Out -0001-11-30 18:30:00 Total Time 0000:00:00 00:00:00

但我希望它返回如下内容:

Time in 2013-04-02 14:05:32 Time Out -0000-00-00 18:30:00 Total Time 0000:00:00 03:30:00

最佳答案

你的问题不是很清楚,我花了很多时间回答错误的问题,直到我仔细查看你的代码,看看你真正想要什么。

据我了解,您将一节课的结束时间作为 MySql Datetime 类型存储在数据库中,并且您想要查找现在与类(class)结束时间之间的剩余时间。

出于此答案的目的,我将忽略时区。

你从

开始
$classTime = DateTime::createFromFormat('Y-m-d H:i:s', '0000-00-00 18:30:00');

要进行有意义的时间比较,需要将 $classTime 的日期部分设置为今天:-

$timeIn = new DateTime();

$year = (int)$timeIn->format('Y');
$month  = (int)$timeIn->format('m');
$day = (int)$timeIn->format('d');

$classTime->setDate($year, $month, $day);

然后您可以进行比较:-

$diff = $timeIn->diff($classTime);

$diff 现在是 DateInterval 的一个实例.

我们现在可以回显信息:-

$start = $timeIn->format('Y-m-d H:i:s');
$end = $classTime->format('Y-m-d H:i:s');
$duration = $diff->format("%Hh, %Im, %Ss");
echo "Time in: $start, Time out: $end, Duration: $duration";

在我运行代码时,给出了以下输出:-

Time in: 2013-04-05 13:22:54, Time out: 2013-04-05 18:30:00, Duration: 05h, 07m, 06s

关于PHP Diff 部分日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771164/

相关文章:

php - PHP 中 preg_replace 的正则表达式

php - 让 PHP 在 64 位操作系统中访问 32 位 COM 对象

c# - 如何将 MFC 的 COleDateTime 转换为 C# DateTime?

c# - 列出日期,添加时间以列出 linq

php - 将时间范围分割成多个部分

php - 将图像上传到 codeigniter 中的 MySQL 数据库 blob

c++ - C++ 中的 MySQL 段错误

mysql - MySQL 中如何汇总多个列

mysql - 如何连接多个表?

android - SimpleDateFormat AM/PM 转换