Get interval seconds between two datetime in PHP?

后端 未结 8 1108
孤街浪徒
孤街浪徒 2021-01-31 07:08

2009-10-05 18:11:08

2009-10-05 18:07:13

This should generate 235,how to do it ?

8条回答
  •  梦如初夏
    2021-01-31 07:28

    Because of unix epoch limitations, you could have problems compairing dates before 1970 and after 2038. I choose to loose precision (=don't look at the single second) but avoid to pass trough unix epoch conversions (getTimestamp). It depends on what you are doing to do...

    In my case, using 365 instead (12*30) and "30" as mean month lenght, reduced the error in an usable output.

    function DateIntervalToSec($start,$end){ // as datetime object returns difference in seconds
        $diff = $end->diff($start);
        $diff_sec = $diff->format('%r').( // prepend the sign - if negative, change it to R if you want the +, too
                    ($diff->s)+ // seconds (no errors)
                    (60*($diff->i))+ // minutes (no errors)
                    (60*60*($diff->h))+ // hours (no errors)
                    (24*60*60*($diff->d))+ // days (no errors)
                    (30*24*60*60*($diff->m))+ // months (???)
                    (365*24*60*60*($diff->y)) // years (???)
                    );
        return $diff_sec;
    }
    

    Note that the error could be 0, if "mean" quantities are intended for diff. The PHP docs don't speaks about this... In a bad case, error could be:

    • 0 seconds if diff is applied to time gaps < 1 month
    • 0 to 3 days if diff is applied to time gaps > 1 month
    • 0 to 14 days if diff is applied to time gaps > 1 year

    I prefer to suppose that somebody decided to consider "m" as 30 days and "y" as 365, charging "d" with the difference when "diff" walk trough non-30-days months...

    If somebody knows something more about this and can provide official documentation, is welcome!

提交回复
热议问题