1

I am trying to get difference between two dates. The format is coming from an API is Y-m-dTH:i:s. Initially, I wanted to output something like this. 02h 10m but when the time difference is too great I had to switch to 01day 12hour 05minute format.

I tried using $duration = 7600 OR $duration = 28800

{{gmdate('t', $duration)}}day {{gmdate('H', $duration)}}hour {{gmdate('i', $duration)}}minute

and {{gmdate('d', $duration)}}day {{gmdate('H', $duration)}}hour {{gmdate('i', $duration)}}minute

This always return day value as 1 when the difference is just 2 hours.

3 Answers 3

2

Make sure to

use Carbon\Carbon;
use Carbon\CarbonInterval;

Convert your API dates into a formatted date using Carbon

$formatted_dt1=Carbon::parse('2019-09-26 00:00:00');
$formatted_dt2=Carbon::parse('2019-09-28 12:12:11');

$totalDuration = $formatted_dt1->DiffInSeconds($formatted_dt2);

echo CarbonInterval::seconds($totalDuration)->cascade()->forHumans();
// output :- 2 days 12 hours 12 minutes 11 seconds

If you want to get day,Minutes,Seconds then.

    $formatted_dt1=Carbon::parse('2019-09-26 00:00:00');
    $formatted_dt2=Carbon::parse('2019-09-28 00:00:00');

    $date_diff=$formatted_dt1->diffInDays($formatted_dt2);
    echo $date_diff.' Day '; //2 days


    $hours_diff = $formatted_dt1->diffInHours($formatted_dt2); 
    echo $date_diff.' Hours '; //48 Hours 


    $Minutesdiff = $formatted_dt1->diffInMinutes($formatted_dt2); 
    echo $Minutesdiff.' Minutes '; //2880 Minutes



    $seconddiff = $formatted_dt1->DiffInSeconds($formatted_dt2); 
    echo $seconddiff.' Seconds '; //172800  Seconds
    exit;
Sign up to request clarification or add additional context in comments.

Comments

1

Try carbon diff function

$past = now();
$future = now()->addHours(2);
$past->diff($future)->format('%dday %hhour %mminute');

Output

"0day 2hour 0minute"

Comments

1

Try this

  $start_date = new DateTime('2012-09-01 04:10:58');
  $since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
  echo $since_start->d.'days '.$since_start->h.'hours '.$since_start->i.'minutes';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.