简体   繁体   中英

How to get date difference in Laravel using Carbon or PHP

I am trying to get difference between two dates. The format is coming from an API is Ym-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.

Try carbon diff function

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

Output

"0day 2hour 0minute"

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 d ay,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;

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM