How to convert an integer to date_time?

Viewed 67

I have a number for average time. I want to return time format like "00:00:12" How can i do it?

a_function(){

  $sum_duration = Model::where('as_user_id',$this->id)->sum('duration');
  //sum_duration = 21
  $week_count = $first_impression->created_at->diffInWeeks($last_impression->created_at);
  //week_count = 2

  $time = date_create(round($sum_duration / ($week_count == 0? 1:$week_count)));
  //false

  return date_format( $time,"H:i:s");
}

The above code is not working. How can i change to show time format like 00:00:00 ((H:i:s))

3 Answers

I assume you have Carbon;

$sum_duration = 21; // from your calculation
$week_count = 2; // from your calculation
$default = Carbon::now()->setTime(0, 0); // set as 00:00:00
$difference = round($sum_duration / ($week_count == 0 ? 1 : $week_count)); // your calculation
$default->addSeconds($difference); // add seconds to 00:00:00

return $default->format('H:i:s');

Edited for seconds

Assuming that the duration is in minutes. You can use gmdate() method to format it.

Example:

gmdate("H:i:s", 123) // returns 00:02:03

Durations aren't dates. But it's an easy calculation nonetheless:

printf('%02d:%02d:%02d', floor($seconds / 3600), floor($seconds / 60 % 60), $seconds % 60);

Demo

(Switch to sprintf() if you want to store or return the value).

Related