PHP:从本地化格式解析日期

Tob*_*bia 17 php parsing localization date

我需要在多语言应用程序中解析日期字符串.每个用户都有自己的语言环境,然后是日期格式.

如何使用:

new DateTime($datestr);
Run Code Online (Sandbox Code Playgroud)

要么

date_parse($datestr);
Run Code Online (Sandbox Code Playgroud)

使用本地化的日期格式?

假设mm/dd/yyyy为EN日期格式,dd/mm/yyyy为IT日期格式,我做了这个测试:

<?php
echo "EN locale<br>\r\n";
setlocale(LC_ALL, 'en_US');
$date="01/02/2015"; //2th Jan
$date_array=date_parse($date);
$mktime=mktime($date_array['hour'], $date_array['minute'], $date_array['second'], $date_array['month'], $date_array['day'], $date_array['year']);
$datetime=new DateTime($date);    
echo date("Y-m-d",$mktime);
echo "<br>\r\n";
echo $datetime->format('Y-m-d');
echo "<br>\r\n";

echo "IT locale<br>\r\n";
setlocale(LC_ALL, 'it_IT');
$date="01/02/2015"; //1th Feb
$date_array=date_parse($date);
$mktime=mktime($date_array['hour'], $date_array['minute'], $date_array['second'], $date_array['month'], $date_array['day'], $date_array['year']);
$datetime=new DateTime($date);    
echo date("Y-m-d",$mktime);
echo "<br>\r\n";
echo $datetime->format('Y-m-d');
Run Code Online (Sandbox Code Playgroud)

结果是SAME输出,使用两种语言环境设置,解析以mm/dd/yyyy格式提供.输出始终是2015 - 01 - 02(2月2日)

Tob*_*bia 8

这就是答案:

$formatter = new IntlDateFormatter("en_US", IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$unixtime=$formatter->parse($date);
Run Code Online (Sandbox Code Playgroud)

这是我之前的测试.

<?php
echo "EN locale<br>\r\n";
$date="01/02/2015"; //2th Jan
$formatter = new IntlDateFormatter("en_US", IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$unixtime=$formatter->parse($date);
$datetime=new DateTime();
$datetime->setTimestamp($unixtime);
echo $datetime->format('Y-m-d');
echo "<br>\r\n";

echo "IT locale<br>\r\n";
$date="01/02/2015"; //1th Feb
$formatter = new IntlDateFormatter("it_IT", IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$unixtime=$formatter->parse($date);
$datetime=new DateTime();
$datetime->setTimestamp($unixtime);
echo $datetime->format('Y-m-d');
echo "<br>\r\n";
Run Code Online (Sandbox Code Playgroud)

不幸的是我无法获得我的赏金... :-)