Question

I am pulling a filename and modified date from a directory. I am having to format the date as ymd h:i so that I can sort the array in date order using the array_multisort.

I wish to then reformat date from ymd h:i to d/m/y h:i; so 140428 11:54 would become 28/04/14 11:54.

I already have a for loop in place going through each array position basically appending it to a variable in order to print it out on the site.

<?php
$filelist = array("");
$datelist = array("");
$html = "";
$x = "";
$days = 250;
$path = 'Directory...';
if ($handle = opendir($path)) {
    while (false !== ($file = readdir ($handle))) {
        if (($file !== ".") && ($file !== "..") && ($file !== "Failed")
                && ($file !== "Complete")) {
            if (filemtime($path.'/'.$file) > (time() - ($days * 24 * 60 * 60 ) ) ) {
                array_push($filelist, $file);
                array_push($datelist, date("ymd h:i", filemtime($path.'/'.$file)));
            }
        }
    }
    closedir($handle);
    array_multisort($datelist, SORT_DESC, $filelist);
    $num = count ($filelist);
    for ($x=0; $x<$num; $x++) {
        $html .= '<tr><td><a href="file://directory/'.$filelist[$x].'">'.$filelist[$x]
            .'</a><br></td><td>'.$datelist[$x].'</td></tr>'."\n\t\t\t\t\t\t\t\t\t\t\t\t";
    }
}
?>
Was it helpful?

Solution

You can create a helper function to parse your custom date time string like this:

<?php

// Helper Function
function parseDate($datetime_str)
{
    list($myDate, $myTime) = explode(' ', $datetime_str);
    list($year, $month, $date) = str_split($myDate, 2);
    return "$date/$month/$year $myTime";
}

// Data Source
$datetime_str = '140428 11:54';

// Usage
var_dump(parseDate($datetime_str));

?>

Output:

enter image description here

OTHER TIPS

I wish to then reformat date from ymd h:i to d/m/y h:i; so 140428 11:54 would become 28/04/14 11:54.

Use DateTime for such operation

$date = DateTime::createFromFormat('ymd h:i', '140428 11:54');
echo $date->format("d/m/y h:i");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top