Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return the timestamps from an indexed array of timestamps with the earliest and latest clock time?

There is a large array with timestamps, e.g.:

$timestamps = array();
for ($i = 0; $i < 5000; $i++) {
    $timestamps[] = mt_rand(strtotime('1900-01-01 00:00:00 am'), strtotime('2100-12-31 11:59:59 pm'));
}

Now I need to return the timestamps with the earliest (min) and latest (max) clock time.

My approach:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

echo date('Y-m-d h:i:s a', min(array_map('callback', $timestamps)));
echo "\n";
echo date('Y-m-d h:i:s a', max(array_map('callback', $timestamps)));

function callback($timestamp) {
    return strtotime(date('h:i:s a', $timestamp));
}

This actually provides the earliest and latest clock time, but of course along with the current date (today).

How to return the original timestamps with the earliest and latest clock time?

>Solution :

You can use next code:

//run array_reduce over array
$res = array_reduce(
    $timestamps, // timestaps array
    function($res, $t) {
        // get time from timestamp
        $time = date('H:i:s', $t);

        // if result min not exists
        // or more then $time store new value to $res['min']
        if (is_null($res['min'][0]) || $time<$res['min'][0])
            $res['min'] = [$time, date('Y-m-d h:i:s a', $t)];


        // if result max not exists
        // or less then $time store new value to $res['max']
        if (is_null($res['max'][0]) || $time>$res['max'][0])
            $res['max'] = [$time, date('Y-m-d h:i:s a', $t)];

        // return updated result
        return $res;
    },
    // define initial $res with null values
    ['min'=>[null, null], 'max'=>[null, null]]
);

Share PHP online

Result:

Array
(
    [min] => Array
        (
            [0] => 00:00:30
            [1] => 1997-05-03 12:00:30 am
        )

    [max] => Array
        (
            [0] => 23:59:36
            [1] => 1983-07-21 11:59:36 pm
        )

)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading