计算两个日期剩余时间的百分比


Calculating percent of time remaining from two dates

到目前为止,我正在尝试获取两个日期之间剩余的时间百分比,以便使用进度条。。

我有下面的代码,我正在输入两个日期并进行求和,但我遇到了一个错误。我不确定这个错误是否是因为日期格式,如果是的话,我可以更改它。

<?
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
$current = '2015-11-03 16:12:15';
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>

我得到以下错误。警告:除以零

strtotime将获取一个日期字符串,并将其转换为unix标准时间(秒)。

<?
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>

我建议使用DateTime对象而不是strtotime。DateTime允许您指定创建时间戳的格式,而不是依靠strtotime来神奇地计算时间戳。这使它更加可靠。

例如:

<?php
$start = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 14:05:15');
$end = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 18:05:15');
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 16:12:15');
$completed = (($current->getTimestamp() - $start->getTimestamp()) / ($end->getTimestamp() - $start->getTimestamp())) * 100;
echo $completed; 
?>

注意:DateTime对象是在PHP 5.3中引入的。任何旧版本都没有DateTime。(老实说,由于多种原因应该更新)

您使用的是字符串(基本上是纯文本)。。。所以你什么都算不出来。您应该使用时间戳(自1970年初以来的毫秒)

http://php.net/manual/fr/function.strtotime.php

$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');

这些都是字符串。你不能减去字符串就指望它能起作用。现在的情况是:

$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';

由于您正在执行-,PHP将这些字符串转换为整数:

$new_start = (int)$start; // 2015
$new_end = (int)$end; // 2015
$new_end - $new_start -> 0

YOu需要将这些值strtotime()返回到unix时间戳中,然后CAN减去这些值,得到以秒为单位的差值。