Get interval seconds between two datetime in PHP?

后端 未结 8 1122
孤街浪徒
孤街浪徒 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:31

    For those worrying about the limitations of using timestamps (i.e. using dates before 1970 and beyond 2038), you can simply calculate the difference in seconds like so:

    $start = new DateTime('2009-10-05 18:11:08');
    $end = new DateTime('2009-10-05 18:07:13');
    $diff = $end->diff($start);
    
    $seconds = ($diff->format('%r%a') * 24 * 60 * 60)
        + $diff->h * 60 * 60
        + $diff->i * 60
        + $diff->s;
    
    echo $seconds; // output: 235
    

    Wrote a blog post for those interested in reading more.

提交回复
热议问题