繁体   English   中英

如何从PHP中获取西班牙语字符串的日期?

[英]How do I get a date from Spanish string in PHP?

我有以下字符串

21 de julio de 2019

我想要解析为可用的DateTime实例。

我尝试过以下各种变体。

$date = DateTime::createFromFormat("d * M * Y", '21 de julio de 2019');

//Setting Locale
setlocale(LC_ALL, 'es_ES');
$date = DateTime::createFromFormat("d * M * Y", '21 de julio de 2019');

但是$date总是false

基于答案

$dateString = '21 de julio de 2019';
echo 'Given date is ' . $dateString . "\n";

//Given date is 21 de julio de 2019

$tz = IntlTimeZone::createTimeZone('Europe/Madrid');
echo 'Tz is ' . $tz->getId() . "\n";

//Tz is Europe/Madrid

$formatter = new IntlDateFormatter(
    'es_ES',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    $tz->getId(),
    IntlDateFormatter::GREGORIAN,
    "d * M * Y");

$parsedDate = $formatter->parse($dateString);

$date = new DateTime($parsedDate);

echo 'Parsed date '. $date->format('d-m-Y');

//Parsed date 25-07-2019

不像我想的那样差不多:/结果$parsedDate是空的,所以今天new DateTime($parsedDate)

尝试使用IntlDateFormatter:

$dateString = '21 de julio de 2019';
echo 'Given date is '.$dateString;
$tz = reset(iterator_to_array(IntlTimeZone::createEnumeration('ES')));
$formatter = datefmt_create(
    'es_ES',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    $tz,
    IntlDateFormatter::GREGORIAN);
echo 'Formatter '.$formatter;
$parsedDate=datefmt_format.format($formatter, $dateString);
echo 'Parsed date '.$parsedDate;

如果正确写入月份的名称,您可以替换它们,然后生成时间戳。

$dateString = '21 de julio de 2019'; // Your input.

$months = [
1 => 'enero',
2 => 'febrero',
3 => 'marzo',
4 => 'abril',
5 => 'mayo',
6 => 'junio',
7 => 'julio',
8 => 'agosto',
9 => 'septiembre',
10 => 'octubre',
11 => 'noviembre',
12 => 'diciembre',
];

$dateString = strtolower($dateString); // Just to be sure that you'll compare lower case strings.
$dateString = str_replace($months, array_keys($months), $dateString); // Replace the month names with numbers.
$dateString = preg_replace("/[^0-9]+/i", ".", $dateString); // Replace all non digit chars with slashes.

$timestamp = strtotime($dateString); // Get a timestamp. You can use it whith a class of your choice.

echo date('d * M * Y', $timestamp); // Output.

因此PHP无法处理外语字符串作为解析输入,只有在输出日期时它才会使用本地化的字符串值。

解决方案是利用第三方库,

https://github.com/jenssegers/date

诸如parse和createFromFormat之类的方法也支持“反向翻译”。 使用已翻译的输入调用这些方法时,它会尝试将其转换为英语,然后再将其传递给DateTime:

$date = Date::createFromFormat('ld F Y', 'zaterdag 21 maart 2015');

或者在我的情况下

$date = Date::createFromFormat('d * M * Y', '21 de julio de 2019');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM