Full Grim Full Grim - 25 days ago 5
PHP Question

PHP array with datetime function to get time in seconds

I have already wrote this function in python (as I have much solid knowledge there), but I need to use this function in PHP (on some codeigniter project - model). So my question is how the fallowing function will look on PHP:



import datetime
from datetime import timedelta
def getMaxValVerify(myList):
intervalTime = myList[len(myList) -1][1] - myList[0][1]
seconds=timedelta.total_seconds(intervalTime)
return seconds





Now to explain what it does, for a list(array) that looks like this :



list = [(41740, datetime.datetime(2016, 6, 20, 18, 00, 00)), (41280, datetime.datetime(2016, 6, 20, 18, 00, 30)), (40500, datetime.datetime(2016, 6, 20, 18, 02, 00))]





It will return the difference in seconds from the first datetime element to the last, in our case from 18:00:00 to 18:02:00 will return:



print getMaxValVerify(list)

120.0




Answer

You should use the DateTime class in PHP, which gives you access to DateIntervals.

Example for 2 dates :

<?php
$dateStart = new DateTime('2016-06-20 18:00:00');
$interval= $dateStart->diff(new DateTime('2016-06-20 18:30:00'));
echo $interval->s.' seconds';

Function example :

<?php
function getInterval($list) // Although you should use 2 parameters instead
{
    $dateStart = min($list);
    $dateEnd = max($list);

    $dateStart = new DateTime($list[0]);
    $interval= $dateStart->diff(new DateTime($list[1]));
    return $interval->s
}

echo getInterval('2016-06-20 18:00:00', '2016-06-20 17:20:00', '2016-06-20 18:30:00') . ' seconds';