我正在从filenames
提取日期。为此,我使用了正则表达式。Php日期时间未知格式 - 仅限日期
日期可以显示为2015-10-31
,20151031
,31-10-2015
,31102015
。
这里是我使用提取的日期代码:
$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]);
使用str_replace
我剥了连字符,因此我最终的两种格式之一,20151031
,31102015
。使用strtotime()
它将转换为1970
。使用PHP的DateTime
我收到以下错误:
Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (01102015) at position 7 (5): Unexpected character'
我需要避免从我个人理解createfromformat
,但我只有一个日期,而不是日期时间,这是示数。
任何人都可以在正确的方向指向我如何格式化这些日期以便稍后在代码中使用。
没关系我了解,他们中的一些碰巧有连字符和一些不。 – Ashley
你总是有这种格式的日期 –
当它不了解日期格式时,strtotime()会给你一个1970年的日期。它不理解'01012015',因此当你删除连字符时它不会拒绝'01-01-2015'。它明白'20150101'然而 – RiggsFolly