Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 日期解析来自未知格式的正确日期_Php_Date_Php Carbon - Fatal编程技术网

Php 日期解析来自未知格式的正确日期

Php 日期解析来自未知格式的正确日期,php,date,php-carbon,Php,Date,Php Carbon,我正在从文件中提取日期。日期的格式各不相同,从美国到欧洲,从破折号到反斜杠 $d1 = '03/12/2017'; $d2 = '12/03/2017'; $d3 = '26/03/2017'; Carbon::parse($d1)->toDateString(); // the month is read as March but it should be read as December Carbon::parse($d2)->toDateString(); // the m

我正在从文件中提取日期。日期的格式各不相同,从美国到欧洲,从破折号到反斜杠

$d1 = '03/12/2017';
$d2 = '12/03/2017';
$d3 = '26/03/2017';


Carbon::parse($d1)->toDateString(); // the month is read as March but it should be read as December
Carbon::parse($d2)->toDateString(); // the month is read as December but it should be March
Carbon::parse($d2)->toDateString(); // throws an ErrorException failing to parse the time due to incorrect format
问题是不知道日期是d/m/Y还是m/d/Y,这会导致按错误的月份对文档进行排序

这些文档来自世界各地的不同企业,我无法控制日期格式


有解决此问题的方法吗?

您应该使用
createFromFormat
请参阅

这样,如果您知道输入字符串是什么,就可以定义应该如何解释该字符串


Carbon扩展了php的类,因此您也可以阅读位于

的DateTime createFromFormat docs,如何判断2017年3月12日是否意味着12月3日的3月12日?如果没有其他信息可以告诉您日期的格式,那么就没有解决此问题的方法(除非您考虑将默认格式作为解决方案之一)。如果你能说出数据来自哪个国家,那么这是否可以确认格式?@JiriHrazdil这就是问题所在,不是吗?美国格式是
MM/DD/YYYY
,这就是为什么它被解释为十二月和三月,而不是三月和十二月。你应该使用
YYYY-MM-DD
,这是无误的。
Carbon::createFromFormat("d/m/Y",$datestring)