Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating DateTime from pattern provided by intl extension PHP

I have a project where date could be entered in different formats by locale for example:

english format: 17/04/2017

korean format 17. 4. 24. I get this data as a string in php. I need this string to be converted to DateTime object somehow. when I have only this string value, locale and the DateType and TimeType values for IntlDateFormatter. The problem that I can't use the \DateTime::createFromFormat() function because the IntlDateFormatter::getPattern() for the english date returns dd/MM/y which is not supported format by DateTime object (it should be d/m/Y)

sample code I have:

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

From this code block i get $dateTime = false

like image 474
Einius Avatar asked Feb 05 '26 06:02

Einius


1 Answers

I know that it is probably to late for the answer, but in case someone else also stuck with it here is the solution: Instead of using getPattern method, use parse on formater, it will return the timestamp, and you will be able to create DateTime object from it. Ex:

$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);
like image 97
Rost Avatar answered Feb 07 '26 21:02

Rost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!