Jump to content

php find earliest date in the format dd/mm/yyyy in a text file


Go to solution Solved by Barand,

Recommended Posts

I have a text file in the following format

03/12/2023 06 This is the text in the line
03/12/2023 06 This is the text in the line
03/12/2023 06 This is the text in the line
03/12/2023 06 This is the text in the line
22/11/2023 06 This is the text in the next line
22/11/2023 06 This is the text in the next line
03/11/2023 06 This is another text in the line
03/11/2023 06 This is another text in the line
03/11/2023 06 This is another text in the line
04/12/2023 06 This is yet another text in the line
04/12/2023 06 This is yet another text in the line

Which is read into an array $data, from this array, I want to output the earliest date which in this case would be 03/11/2023

$earliestDateTs = false;
foreach($data as $line)
{
	$dateStr = substr($line, 0, 10);  //Get just the date part of the string
	$dateTs  = strtotime($dateStr);   //Convert the date string to a timestamp
	if(!$earliestDateTs) { $earliestDateTs = $dateTs; }  //If earliestDateTs not set (i.e. first iteration) set to this line's timestamp
	$earliestDateTs = min($dateTs, $earliestDateTs);  //Set earliestDateTs to the minimum of the current value or this line's timestamp
}

echo "Earliest date: " . date('m/d/Y', $earliestDateTs);

 

  • Solution

Alternatively

usort($data, fn($a, $b) => isoDate($a) <=> isoDate($b));
echo $data[0];                                                        //--> 03/11/2023 06 This is another text in the line

function isoDate($text)
{
    $d = substr($text, 0, 10);
    return DateTime::createFromFormat('d/m/Y', $d)->format('Y-m-d');
}  

 

  • Like 1

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.