Search code examples
phplaravelphp-carbon

StartDate - EndDate is same as EndDate - StartDate in Carbon


In general scenario

$a = 100;
$b = 150;
/*  
    Output of $a - $b = (100 – 150) = -50 (Negative value)
    Output of $b - $a = (150 – 100) = 50 (Positive value)
*/

I am trying to get difference between two dates using Carbon as below…

$start = Carbon::now(); 
$end = $start->copy()->addMinute(2);
echo $start->diffInSeconds($end); /* output is 120 */
echo $end->diffInSeconds($start); /* output is 120 */

Question is why diffInSeconds returning same value in both cases? Might be I am missing something here.

And what should be correct method to achieve correct values.

Please help me to understand this.


Solution

  • From the Carbon docs:

    Each function below has a default first parameter which is the Carbon instance to compare to, or null if you want to use now(). The 2nd parameter again is optional and indicates if you want the return value to be the absolute value or a relative value that might have a - (negative) sign if the passed in date is less than the current instance. This will default to true, return the absolute value.

    So to get negative values (where appropriate), set the optional second parameter to false.