简体   繁体   中英

How to substract two times in php using carbon?

I have two times and I want to subtract them by using a PHP built-in function or Carbon. For example, I have following times:

  1. 00:05:10 , ie 5 Minutes 10 Seconds
  2. 00:03:10 , ie 3 Minutes 10 Seconds

If I subtract them, the total time would be 00:08:20. Can someone kindly guide me how I can make such a subtraction?

经过比较和减去后,转换为我认为的时间戳

If you convert both times to unix timestamps, take away a "base timestamp" (For 00:00:00) from each, and then add them together you will get the number of seconds value for the 2 timestamps. Through some simple operations we can then get the total number of hours, minutes, and remaining seconds, then format them in your input style.

function add_times($a, $b) {
    $base = strtotime('00:00:00');
    $seconds = (strtotime($a) - $base) + (strtotime($b) - $base);

    $hours = floor($seconds / 3600);
    $minutes = floor($seconds / 60) % 60;
    $seconds = $seconds % 60;

    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

echo add_times('00:05:10', '00:03:10');

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