PHP -使用区域设置字符串解析datetime


PHP - Parse datetime with locale strings

我想解析像'Ayer, 16:08'这样的日期时间,它在西班牙语中是'Yesterday, 16:08'。

我已经试过了

$dateString = 'Ayer, 16:08';
setlocale(LC_ALL, 'es');
$time = strtotime($dateString);
echo date('d-m-Y H:i', $time);

但是它回显

01-01-1970 00:00

然而,如果我用英文字符串做,它工作得很好:

$dateString = 'Yesterday, 16:08';
$time = strtotime($dateString);
echo date('d-m-Y H:i', $time);

是语言环境的问题吗?

谢谢

你需要在确定日期之前把它翻译成英文。

创建一个包含西班牙语单词的数组,另一个包含PHP识别的对应英语翻译的数组。然后只需使用$dateString运行str_ireplace()。

应该这样做:

$spanish = array("spanish1", "spanish2", "spanish3");
$english = array("en_translation_of_spanish1", "en_translation_spanish2", "en_translation_of_spanish3");
$dateString = str_ireplace($spanish, $english, 'Ayer, 16:08');

在Manual中我看不到任何关于其他语言的内容。所以你需要翻译它,就像Zumi说的

现在有IntlDateFormatter用于此目的,参见此stackoverflow答案:https://stackoverflow.com/a/32265594/682317

复制到这里:

这就是答案:

$formatter = new IntlDateFormatter("en_US", IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$unixtime=$formatter->parse($date);

这是我之前的答案。

<?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";

不幸的是,我不能得到我的赏金…: -)