Php Datetime Format unknown - Date only
source link: https://www.codesd.com/item/php-datetime-format-unknown-date-only.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Php Datetime Format unknown - Date only
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 DateTime
I 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.
Do not strip hyphens. So, the next code will work fine.
$date1 = new \DateTime('31-10-2015');
$date2 = new \DateTime('2015-10-31');
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK