时间差异的精确样式(php)


Exact styling of a difference in time (php)

很容易得到两次(格式:H:i:s)的分秒差,我是从这个网站上的另一个问题中得到的。

我是这样尝试的:

$start_date = new DateTime('04:10:58');
$since_start = $start_date->diff(new DateTime('10:25:00'));
echo $since_start->h.':';
echo $since_start->i.':';
echo $since_start->s;

但输出:

下午6:14:2

我觉得这看起来不太好。我希望它看起来像:06:14:02

我也想使用当前时间,而不是给定的时间,但我注意到上面的代码不起作用。

$start_date = date("H:i:s");
$since_start = $start_date->diff(new DateTime('10:25:00'));
echo $since_start->h.':';
echo $since_start->i.':';
echo $since_start->s;

输出:

致命错误:在非对象上调用成员函数diff()

我有两次:一个时间是当前时间:date("H:i:s"),另一个是$time0,它包含例如时间11:24:00(来自数据库)。

DateInterval的内部没有格式化,应该使用DateInterval::format函数:

$start_date = new DateTime('04:10:58');
$since_start = $start_date->diff(new DateTime('10:25:00'));
echo $since_start->format('%H:%I:%S');

在第二个示例中,您使用了一个PHP字符串(因为date()返回的是字符串,而不是对象),并试图将其视为DateTime对象,这就是为什么会出现错误的原因。您应该初始化一个空的DateTime对象,该对象将默认为now:

$start_date = new DateTime(); // or DateTime('now')
$since_start = $start_date->diff(new DateTime('10:25:00'));
echo $since_start->format('%H:%I:%S');

如果您从数据库启动$start_date值,比如$time0,您可以将其直接传递到DateTime构造中,这将很好地将其转换为适当的DateTime对象:

$start_date = new DateTime($time0);
$since_start = $start_date->diff(new DateTime('10:25:00'));
echo $since_start->format('%H:%I:%S');