hirsa
hirsa

Reputation: 3

Calculate the time difference of two rows in laravel

I want calculate time different between 2 row and calculate rank. this is my code:

 public function testtima($sid,$rid){
        $calcs=users::where([['si',$sid]])->first();
        $calcr=users::where([['ri',$rid]])->first();
        $stime=$calcs['created_at'];
        $rtime=$calcr['created_at'];
        $show['stime']=$stime;
        $show['rtime']=$rtime;
        $show['now']=carbon::now();
        return $show;
    }

how can i calculate $rtime-$stime ?

Upvotes: 0

Views: 411

Answers (2)

Murali K N
Murali K N

Reputation: 1

$row1= "2007-03-24";
$row2= "2009-06-26";

$diff = abs(strtotime($row2) - strtotime($row1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Upvotes: 0

TsaiKoga
TsaiKoga

Reputation: 13404

Use Carbon's method, diffInSeconds, diffInDays or diffInMonths etc:

public function testtima($sid,$rid){
    $stime = users::where('si',$sid)->first()->created_at;
    $rtime = users::where('ri',$rid)->first()->created_at;
    $diff = (new Carbon($stime))->diffInSeconds($rtime);
    //$diff = (new Carbon($stime))->diffInDays($rtime);   
    return $diff;
}

Upvotes: 1

Related Questions