Search code examples
phparraysdateforeachstrtotime

Php format an array of dates


I'm trying to make a function that formats dates from nested arrays lying in the same array. I'm able to locate and echo the values in the array, however I'm struggling to format the date into the way I want to print it out. The way my code is set up I have one function that goes into the array, iterates over each of the nested arrays and prints out the value attached to the key that it is set to look for.

That works fine, but my other function is meant to take the date and format it into the way I wish it to print out with the date function and just no go. I've got a few ideas as to why this is the case, but I know I don't know which is why I'm hoping someone can help. Thanks in advance, I appreciate anyone trying to help me on this. I'm new to php so it's been an interesting foray.

I've used the php date, strtotime, and date_create_from_format functions to attempt to take the date and format it into a date the way I want to.

// Example clip from array
$Full_List_Of_Recover_Items = array (
  0 => 
  array (
'ActionTimeStamp' => '2018-07-23 15:17:23'
  )
);


//  End format would look like July 23, 2018 3:17pm


<?php

function valGet($arr, $value)
{
    foreach($arr as $row)
    {
        foreach($row as $key => $val)
        {
            if ($key == $value)
            {
                if ($val == NULL)
                    echo "empty";
                else
                echo $val;
            }
        }
    }
}
function timeFormat($timeStamp)
{
// split the array value to set up date
$first = explode(" ", $timestamp);
$second = explode("-", $first);
$third = explode(":", $second);

//  format the date and convert it attempt
$stringTime = strtotime("D, F, d, Y, g, i", $timestamp);
$date = date_create_from_format("Y-m-d H:i:s");
echo date($date($stringTime));

}

?>


// invocation on html

  <p>
    <?php
        echo timeFormat(valGet($Full_List_Of_Recover_Items, 'ActionTimeStamp'));

    ?>
    </p>

Solution

  • You need to modify your timeFormat function. Just use strtotime:

    $timeStamp = '2018-07-23 15:17:23';
    echo date("F j, Y, g:i a",  strtotime($timeStamp)); // prints July 23, 2018, 3:17 pm
    

    And here you can see the documentation for all kind of format: PHP manual date

    Reference: strtotime