php - 从国际扩展 PHP 提供的模式创建 DateTime

标签 php datetime locale intl

我有一个项目,其中可以按区域设置以不同格式输入日期,例如:

英文格式:17/04/2017

韩文格式 17。 4. 24. 我在 php 中将此数据作为字符串获取。 我需要以某种方式将此字符串转换为 DateTime 对象。当我只有此字符串值、区域设置以及 IntlDateFormatter 的 DateType 和 TimeType 值时。 我无法使用\DateTime::createFromFormat() 函数的问题,因为英文日期的 IntlDateFormatter::getPattern() 返回 dd/MM/y DateTime 对象不支持格式(应为 d/m/Y)

示例代码:

$locale = 'en_GB';
$value = '17/04/2017';     
$formatter = new IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
$format = $formatter->getPattern();
$dateTime = \DateTime::createFromFormat(format, $value);

从这个代码块我得到 $dateTime = false

最佳答案

我知道答案可能已经晚了,但如果其他人也坚持使用这里的解决方案:而不是使用 getPattern 方法,而是使用 parse 在 formater 上,它将返回时间戳,您将能够从中创建 DateTime 对象。 例如:

$locale = 'en_GB';
$value = '17/04/2017';
$formatter = new IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);

$timestamp = $formatter->parse($value);
assert($timestamp !== false);
$dateTime = (new \DateTime())->setTimestamp($timestamp);

关于php - 从国际扩展 PHP 提供的模式创建 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43589982/

相关文章:

c - 使用 setlocale() 和 gettext() 在 Ubuntu 上测试语言环境

php - 如何避免 if/elseif 重复?

php - RecursiveIteratorIterator 和 RecursiveDirectoryIterator 到嵌套的 html 列表

php - yii 不保存模型

java - Groovy - 计算从当前时间开始是否经过了特定分钟

java - 输入字符串 : "15,7" 的 NumberFormatException

php - 是否可以针对 PHP 中的多个模式验证 XML?

mysql - 将文本时间戳转换为日期

php - 将mysql时间戳转换为php用户友好版本

java - 在 java 程序中传播 locale 对象的良好实践