3

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

Einius
  • 1,352
  • 2
  • 20
  • 45
  • `\DateTime::createFromFormat(format`? Is it? Maybe `$format`? – u_mulder Apr 24 '17 at 13:52
  • the problem is that IntlDateFormatter returns wrong format. DateTime doesnt support it. – Einius Apr 24 '17 at 13:55
  • Why is `17. 4. 24.` in this question? When its comes to php its all about `17/04/2017`? And use it like this `$dateTime = \DateTime::createFromFormat('d/m/yy', $value); print $dateTime->format('d-m-y');//17-04-17` – JustOnUnderMillions Apr 24 '17 at 13:57
  • the thing is why `17. 4. 24.` here it's because a lot of different locales could be used. and for different locales different formats are used. I get a date as a string in one format. I get a locale for the submitted date. but I cant create DateTime from it. – Einius Apr 24 '17 at 14:04

1 Answers1

2

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);
Rost
  • 21
  • 3