我有2个日期时间,我想以分钟为单位计算差值:
$date_reservation=strtotime($_POST['date_reservation']);;
$dt = new DateTime();
$date_annulation = strtotime($dt->format('Y-m-d H:i:s'));
$attente = (round(abs($date_annulation - $date_reservation)/60)%60);它只取不含小时的分钟的差值。
我已经尝试过这个函数(来自php文档)
$interval = $date_annulation->diff($date_reservation);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d'); 但它不工作(错误500)
发布于 2016-05-20 20:13:39
如果您意识到使用这种方法可能会有不准确之处,您可以只比较Unix时间戳::
$date_reservation = strtotime('2016-05-20 13:30');
$date_annulation = strtotime('now');
$diff_minutes = round(abs($date_annulation - $date_reservation)/60, 0);您的代码中唯一的问题是,您mod 60您的分钟(%60)。当然,这只给了你比整个小时更长的时间。
请注意,strtotime使用在运行此代码的机器上设置的时区来解释日期时间字符串。您可以使用date_default_timezone_set()在代码中进行设置。
请参阅ideone.com上的示例。
发布于 2016-05-21 03:14:30
您的问题是$date_annulation不是DateTime对象。使用strtotime保持简单
<?php
$date_reservation = strtotime($_POST['date_reservation']);
$date_annulation = strtotime('now');
$diff_minutes = ($date_annulation - $date_reservation)/60;
echo $diff_minutes;发布于 2016-05-21 04:21:12
如果响应为500 Internal Server Error,则表示您的PHP代码存在问题。检查服务器日志文件(Apache的error_log、PHP的php_errors.log),找出确切的位置(文件和行)和原因。
同时,您从文档中复制的代码不起作用,因为您试图对一个数字(由strtotime()返回的值)调用DateTime类的方法。它不是这样工作的。
但是,如果您使用DateTime (和相关的)对象,它确实可以工作:
$date_reservation = new DateTime($_POST['date_reservation']);
$date_annulation = new DateTime('now');
$interval = $date_annulation->diff($date_reservation);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d'); https://stackoverflow.com/questions/37346241
复制相似问题