如何在php中计算日期时间


How to calculate datetime in php

我想申请预订其中一个字段是日期和时间例如:长时间预订和预订

预订日期:2013年12月18日15:30:00长期预订:6小时

结果将是18-12-2013 21:30:00

如果消息的日期和旧订单。几个小时最后是0点30分。它已经更改了日期。

预订日期:2013年12月18日20:30:00长期预订:5小时

结果将是2013年12月18日01:30:00

如何在PHP中实现它?

对不起,我还是个新手:-)

我的php代码

$date_booking = $_POST['datebooking'];
$long_time = $_POST['long']; // its contents were 1, 2, 3, 4, and so on
$result = strtotime($date_booking) + $longtime;

使用strtotime()将日期字符串更改为整数(自1970-01-01以来的秒数)。

将长预订从小时转换为秒(*60*60),然后进行添加并使用date('Y-m-d H:i:s', $endTime)将其转换回日期时间字符串。

注意:您必须首先将字符串"DD-MM-YYYY"转换为"YYYY-MM-DD"才能使其工作为

使用您的代码编辑

$date_booking = $_POST['datebooking']; // need to be formatted as "YYYY-MM-DD HH:II:SS" (for example) 
$long_time = $_POST['long']; // its contents were 1, 2, 3, 4, and so on
$long_time_sec = $long_time * 3600; // convert hours to seconds
$result = strtotime($date_booking) + $long_time_sec; 
echo 'end of booking is '.date('Y-m-d H:i:s', $result);

有一个函数strtotime,它接受不同格式的日期,您可以在其中添加一些时间。在你的情况下,你可以做:

$mydate = strtotime("18-12-2013 15:30:00 + 6 hours");

然后,从1970-01-01(UNIX时间)开始有几秒钟的时间,您可以使用date函数将其转换为您想要的任何格式:

$returnValue = date('d-m-Y H:i:s', $mydate);

注意:我不明白您是否有"文本订单",如预订日期:XXXX和长期预订:X小时。如果是这种情况,您可以使用函数str_replace或类似函数来去掉"预订日期:"answers"长期预订:"部分:

$order = str_replace(array('date of booking : ', 'And long booking :'),
                     '',
                     $order);

新的PHP代码应该使用DateTime函数。strtotime()本质上没有什么问题,但DateTime将为您处理诸如DST更改之类的事情,而不会带来任何麻烦。在这种情况下,你的代码应该是这样的:-

$date_booking = 'DateTime::createFromFormat('d-m-Y H:i:s', $_POST['datebooking']);
$long_time = new 'DateInterval("PT{$_POST['long']}H");
$date_booking->add($long_time);
echo "Booking ends at " . $date_booking->format('Y-m-d H:i:s');

请参阅工作示例。

在此处阅读有关设置DateTime格式的更多信息。