<?php
$filenameNew = 'PX20170713_103320_2651093_00001';
$filenameOld = '5956e5781e4f1-20170630_233347_5712837_00001.xml';
//$timeslug = implode(array_slice(explode('_', rtrim(basename($fileToProcess), ".xml" )), 0, 2));
//$datetime = date('c', strtotime($timeslug));
/**
* Get a date time object from an AX filename.
*
* Example filename: PX20170713_103320_2651093_00001.xml
*/
function getDateFromFilename(string $filename): ?DateTime
{
// Find the first block of 4-2-2 numbers.
$dateRegexp = '/([0-9]{4})([0-9]{2})([0-9]{2})/';
// Find the first block of 2-2-2 numbers
$timeRegexp = '/([0-9]{2})([0-9]{2})([0-9]{2})/';
// We could do the regex directly to the filename but by extracting
// the date and time from the filename string we retain a level of
// safety in that we can not accidentally regexp the wrong value.
try {
list($date, $time) = explode('_', $filename);
} catch (\Throwable $t) {
throw new \Exception(sprintf(
'Could not split the date up from the filename for %s',
$filename
));
}
// Regex the date and drop the first array index(the entire string block)
try {
preg_match($dateRegexp, $date, $dateParts);
unset($dateParts[0]);
} catch (\Throwable $t) {
throw new \Exception(sprintf(
'Could not extrapolate the date from the filename %s',
$filename
));
}
// Regex the time
try {
preg_match($timeRegexp, $time, $timeParts);
unset($timeParts[0]);
} catch (\Throwable $t) {
throw new \Exception(sprintf(
'Could not extrapolate the time from the filename %s',
$filename
));
}
// Create a new datetime instance and set the date from the regex results.
try {
$dateTime = new \DateTime();
$dateTime->setDate($dateParts[1], $dateParts[2], $dateParts[3]);
$dateTime->setTime($timeParts[1], $timeParts[2], $timeParts[3]);
} catch (\Throwable $t) {
throw new \Exception(sprintf(
'Could not build the date time from the filename %s',
$filename
));
return null;
}
return $dateTime;
}
var_dump(getDateFromFilename($filenameNew));