我想减去2个日期,并在几分钟内得到结果,如下面的代码给出了我想要的答案。
$to_time = strtotime("2017-03-27 17:31:40");
$from_time = strtotime("2017-03-27 18:32:40");
echo "sunolo1: ".round(abs($to_time - $from_time) / 60,2). " minute";
但是当我尝试使用php从mysql中检索动态日期时它不起作用它返回0.(我的表中的日期是时间戳)
$d = new DateTime("now", new DateTimeZone("Europe/Athens"));
$dateM = $d->format("Y-m-j H:i:s");
$result = mysqli_prepare($con, "SELECT date FROM mytable WHERE id= ? ");
mysqli_stmt_bind_param($result, 'i', $ids);
mysqli_stmt_execute($result);
mysqli_stmt_bind_result($result, $ddd);
while(mysqli_stmt_fetch($result)){
$sunolo_krathshs = round(abs($ddd - $dateM) / 60,2);
echo "sunoloo: ".$sunolo_krathshs;
}
答案 0 :(得分:2)
您需要将$ ddd的值解析为DateTime对象,因为最简单的方法是比较DateTime对象。
$date = new DateTime();
$ddd = $date->setTimestamp($ddd);
$sunolo_krathshs = round(abs($ddd - $d) / 60,2);
答案 1 :(得分:2)
请检查一下。
<?php
$datetime1 = new DateTime("2017-03-27 17:31:40");
$datetime2 = new DateTime("2017-03-27 18:32:40");
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
?>
&#13;
答案 2 :(得分:1)
在传递日期值时使用strtotime函数进行计算。像这样:
$sunolo_krathshs = round(abs(strtotime($dateM) - strtotime($ddd)) / 60,2);
答案 3 :(得分:1)
使用DateTime类可以非常简单
$result = mysqli_prepare($con, "SELECT date FROM mytable WHERE id= ? ");
mysqli_stmt_bind_param($result, 'i', $ids);
mysqli_stmt_execute($result);
mysqli_stmt_bind_result($result, $ddd);
$to_time = new DateTime("now", new DateTimeZone("Europe/Athens"));
while(mysqli_stmt_fetch($result)){
// probably want UTC as date times are stored on the db in UTC
// but you may need to experiment with timezones here
$from_date = DateTime::createFromFormat('Y-m-d H:i:s', $ddd, new DateTimeZone("UTC"));
echo round(abs($to_date->getTimestamp() - $from_date->getTimestamp()) / 60,2). " minute";
}
答案 4 :(得分:-3)
变量$ ids没有分配值操作...