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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With