It is required to know the difference in seconds between two DateTime objects. By a certain amount of ordeal, the following happened:

<?php session_start(); $_SESSION['previousAccessTime'] = $_SESSION['currentAccessTime']; $_SESSION['currentAccessTime'] = new DateTime(); echo $_SESSION['previousAccessTime']->format("h:i:s"), " - ", $_SESSION['currentAccessTime']->format("h:i:s"), "<br>"; $interval = strtotime($_SESSION['currentAccessTime']->format("h:i:s")) - strtotime($_SESSION['previousAccessTime']->format("h:i:s")); echo $interval; ?> 

It works and the difference in seconds between the two marks is placed in the $ interval ... But the feeling is that I am doing something wrong. Perhaps this feeling is connected with the method of obtaining this difference, in which I get a string from a DateTime object, and then turn it into a time object. As far as this solution to the problem is crooked, the feeling that I have a pile of a crutch does not leave me, and I do not want to do that.

    1 answer 1

    You can use getTimestamp() to immediately get the number of seconds (since 1970).

     $diff = $dateTimeLater->getTimestamp() - $dateTimeBefore->getTimestamp() 
    • I am not so much interested in the question "how can I", how many "how I NEED". That's the whole problem. And arithmetic operation on such numbers does not hurt performance? - Devolutheist
    • @Devolutheist, well, this is what your version does with format() (and this is without taking into account converting back to a number), but what getTimestamp() does is one and two times . An arithmetic operation doesn’t really affect anything here (especially compared to rebuilding strings and subsequent parsing). - Surfin Bird
    • plus, in my version, an annoying problem with eating memory was found, after 200 requests, 20KB was added. - Devolutheist