Get interval seconds between two datetime in PHP?

后端 未结 8 1104
孤街浪徒
孤街浪徒 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.

    0 讨论(0)
  • 2021-01-31 07:32

    With DateTime objects, you can do it like this:

    $date = new DateTime( '2009-10-05 18:07:13' );
    $date2 = new DateTime( '2009-10-05 18:11:08' );
    
    $diffInSeconds = $date2->getTimestamp() - $date->getTimestamp();
    
    0 讨论(0)
提交回复
热议问题