Domanda

That get i use code:

$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);

But in var_dump($diff); i see:

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) 
                           }

Tell me please how get y,m,d,h,i,s with zeros, that ,ex., $diff['h'] will be '02' instead of '2' ?

È stato utile?

Soluzione

Just use "format" method of DateInterval: http://php.net/manual/ru/dateinterval.format.php

eg:

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

If you only want to get one of attributes, use sprintf or str_pad:

sprintf('%02d', $diff->d);

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

Altri suggerimenti

you can check the string length if its not 2 then add a 0(zero) string, like follows

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

You are doing a few things wrong here. You don't need to use date() with DateTime objects and DateTime::createFromFormat() is more appropriate for your use case. Your example code should look like this:-

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

Then you can output in any format you wish:-

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

Which will produce something like:-

Time difference = 00 Years 00 Months 06 Days 23 Hours 17 Minutes 38 Seconds
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top