PHP - Parse datetime with locale strings

百般思念 提交于 2020-01-05 03:36:07

问题


I want to parse datetimes like 'Ayer, 16:08' which is 'Yesterday, 16:08' in spanish.

I have tried this

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

but it echoes

01-01-1970 00:00

Nevertheless, if I do it with english strings it works just fine:

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

Is it a problem with locale?

Thanks


回答1:


You'll need to translate it into English before making the date.

Create an array with the Spanish words, and another with the corresponding English translations, as recognised by PHP. Then simply run str_ireplace() with $dateString.

Something like this should work:

$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');



回答2:


In Manual I can't see anything about others languages. So, you need translate it, as Zumi said




回答3:


These days there is IntlDateFormatter for this purpose, see this stackoverflow answer: https://stackoverflow.com/a/32265594/682317

Copied here:

This is the answer:

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

And this is the previous test working with my answer.

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

Unfortunately I cannot earn my bounty... :-)



来源:https://stackoverflow.com/questions/6954003/php-parse-datetime-with-locale-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!