简体   繁体   English

PHP和MySQL中的日期时间之间的差异

[英]Difference between datetimes in PHP and MySQL

I have 2 dates from mysql with datetime format. 我有两个来自mysql的日期时间格式的日期。

Date 1 is: 日期1是:

"2012/09/28 09:28:00" (column name is departure_date)

and Date 2 is: 和日期2是:

"2012/09/29 10:48:00" (column name is return_date)

So how to get a result like this: "25 hours 20 minutes" 那么如何得到这样的结果: "25 hours 20 minutes"

I don't care about the seconds. 我不关心秒。

I'm using MySQL and PHP for the programming language. 我正在使用MySQL和PHP作为编程语言。

Date difference function already exists 日期差异功能已存在

SELECT DATEDIFF('2007-10-04 11:26:00','2007-10-04 11:50:00')

Also you can try TimeDiff 你也可以尝试TimeDiff

SELECT TIMEDIFF('2007-10-05 12:10:18','2007-10-05 16:14:59') AS duration;

So in your case you have the option to use these two functions like this 因此,在您的情况下,您可以选择使用这两个函数

SELECT TIMEDIFF(departure_date,return_date) AS duration;
SELECT DATEDIFF(departure_date,return_date) AS duration;

You could use DateInterval class. 您可以使用DateInterval类。

$date1 = new DateTime("2012/09/28 09:28:00");
$date2 = new DateTime("2012/09/29 10:48:00");

$diff = $date1->diff($date2);
echo $diff->format('%d days %h hours %i minutes');

Check here for the format. 点击此处查看格式。

You can do it example by this: 你可以这样做:

$date1 = "2012/09/28 09:28:00";
$date2 = "2012/09/29 10:48:00";

$difference = abs(strtotime($date2)-strtotime($date1));

$hours = floor($difference / (60*60));
$minutes = floor(($difference - $hours * 60*60) / 60);

echo "{$hours} hours {$minutes} minutes";

And it will give you exactly what are you looking for: 它会准确地告诉你你在寻找什么:

25 hours 20 minutes 25小时20分钟

try this: 尝试这个:

select concat(substr(mt,1,locate('.',mt)-1),' hours') hours,
       concat(ceil((substr(mt,locate('.',mt)+1) * .60)/100 ),' minutes') 
                                                                     as minutes
from (
select TIMESTAMPDIFF(MINUTE,
                      '2012/09/28 09:28:00','2012/09/29 10:48:00')/60 as mt)a


SQL Fiddle demo SQL小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM