php date()diff()如何获取一个包含零的日期


php date() diff() How to get a date with zeros?

我使用代码:

$then = new DateTime(date('Y-m-d H:i:s', $seconds_end));
$now = new DateTime(date('Y-m-d H:i:s', time()));
$diff = $then->diff($now);

但在var_dump($diff);中,我看到:

object(DateInterval)#4 (8) { 
                           ["y"]=> int(0) 
                           ["m"]=> int(0) 
                           ["d"]=> int(6) 
                           ["h"]=> int(2) 
                           ["i"]=> int(1) 
                           ["s"]=> int(17) 
                           ["invert"]=> int(1)
                           ["days"]=> int(6) 
                           }

请告诉我如何得到零的y,m,d,h,i,s,例如。,$diff['h']将是'02'而不是'2'

只需使用DateInterval的"format"方法:http://php.net/manual/ru/dateinterval.format.php

例如:

$diff->format('%Y-%M-%D %H:%I:%S');

如果您只想获得其中一个属性,请使用sprintf或str_pad:

sprintf('%02d', $diff->d);
str_pad($$diff->d, 2, '0', STR_PAD_LEFT);

您可以检查字符串长度,如果不是2,则添加一个0(零)字符串,如下所示

if(strlen($diff->h)==1) 
{
$new_hr='0'.$interval->h;   
}
echo $new_hr;

您在这里做错了一些事情。您不需要将date()与DateTime对象一起使用,DateTime::createFromFormat()更适合您的用例。您的示例代码应该如下所示:-

$then = DateTime::createFromFormat('Y-m-d H:i:s', $seconds_end);
$now = new DateTime(); // Defaults to current date & time
$diff = $then->diff($now);

然后你可以以任何你想要的格式输出:-

echo $diff->format("Time difference = %Y Years %M Months %D Days %H Hours %I Minutes %S Seconds");    

这将产生类似的东西:-

Time difference = 00 Years 00 Months 06 Days 23 Hours 17 Minutes 38 Seconds