Php Datetime Unknown Format - Date Only

Wednesday, November 4, 2015

I am working on extracting the date from filenames. For this I have used regex.



The dates can appear like 2015-10-31,20151031, 31-10-2015,31102015.



Here is the code I am using to extract the date:



$re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/';
$str = "20151001-importsrc1.txt";
$str = "2015-10-01-importsrc1.txt";
$str = "01-10-2015-importsrc1.txt";
$str = "importsrc1-2015-10-01.txt";
$str = "importsrc1-01102015.txt";
$str = "importsrc1-01-10-2015.txt";
preg_match($re, $str, $matches);
$date = str_replace("-", "", $matches[0]);


Using the str_replace I am stripping the hyphens, therefore I end up with one of two formats, 20151031, 31102015.



Using strtotime() it is converting to 1970. Using PHP's DateTimeI received the following error:




Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (01102015) at position 7 (5): Unexpected character'




I need to avoid createfromformat from what I understand, but as I only have a date and not datetime this is erroring.



Can anyone point me in the right direction as to how I could format these dates for use later in the code.

0 comments:

Post a Comment