質問

I have two dates and i want to get the amount of time between them.
I try this:

$created_dt="2014-01-30 09:27:02";    
$done_dt="2014-01-30 16:29:38";

$created_dt=strtotime($created_dt); //1391066822
$done_dt=strtotime($done_dt); //1391092178
$runing_time= $created_dt-$done_dt; //25356
$runing_time= date('H:i',$runing_time);
echo $runing_time; //  "09:02" <----------??????? 

why is $runing_time = 09:02 ???

what is a good way around this?
thanks

Part 2
how can i sum a few $intervals together? and after that get their average?
I try:

   $average_time;
   foreach($tasks as $task)
   {

   $date1 = new DateTime($task['start']);
   $date2 = new DateTime($task['end']);
   $interval = $date1->diff($date2);
   $runing_time=$interval->format("%h hours, %i minutes, %s seconds");
   $average_time+=$interval ;
   }
   $final_average_time=average_time/4;

obviously my code didnt work because $interval is a an object.

役に立ちましたか?

解決 3

I know, you better use DateTime(), but no one here is talking about your issue and why are you getting the wrong result .

Its because date() function get 2nd parameter as time stamp and returns the date : 1970-1-1 00:00:00 GMT + given time stamp , pay attention to GMT part. it means if your time zone is +2, then echo date("Y-m-d H:i:s",0) returns 1970-1-1 2:00:00 , not 1970-1-1 00:00:00.

So, the result that you are getting, is 07:02(real different) + 2 hours(your time zone) . if you insist of getting the result using date(), you must change the last lines to:

$runing_time= $done_dt - $created_dt - 2*3600;
$runing_time= date('H:i',$runing_time); 
//returns 07:02

他のヒント

Use DateTime() and DateInterval() for date math. Much easier to do.

$date1 = new DateTime("2014-01-30 09:27:02");
$date2 = new DateTime("2014-01-30 16:29:38");
$interval = $date1->diff($date2);
echo $interval->format("%h hours, %i minutes, %s seconds");

See it in action

Try using DateTime , the diff method returns the difference between two DateTime objects

$createDate = DateTime::createFromFormat("Y-m-d H:i:s", $created_dt);
$endDate = DateTime::createFromFormat("Y-m-d H:i:s", $done_dt);
$interval = $createDate->diff($endDate2);
echo $interval->format('%R%a days %H hours %i Minutes and %s Seconds');
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top