How to convert string to DateTime if the language is NOT English

Viewed 130

There is a date and time string in the format "2 листопада 2020, 21:00, п’ятниця" I want to convert it to DateTime. I tried converting.

    setlocale(LC_ALL, 'uk_UA');
$t = '2 листопада 2020, 21:00, п’ятниця';
$date = date_create_from_format('j F Y, H:i, l', $t);

If the language is English, the date is converted, if Ukrainian does not work. How to set the language for conversion.

1 Answers

I think the setLocale settings don't affect the functionality of the DateTime class. This class requires names in English. One simple way to solve the problem is to translate the month names and ignore the day name. If ignore the Day Name an incorrect name as in the example cannot generate an error.

$t = '2 листопада 2020, 21:00, п’ятниця';

$trans = [
  'січня' => "January",
  'лютого' => "February",
  'березня' => "March",
  'квітня' => "April",
  'травня' => "May",
  'червня' => "June",
  'липня' => "July",
  'серпня' => "August",
  'вересня' => "September",
  'жовтня' => "October",
  'листопада' => "November",
  'грудня' => "December",
];


$inputEn = strtr($t, $trans);
$date = date_create_from_format('j F Y, H:i, *', $inputEn);

var_dump($date);
//object(DateTime)#1 (3) { ["date"]=> string(26) "2020-11-02 21:00:00.000000" ...

This solution works independently of the setlocale settings.

The algorithm shown above is built into a PHP extension called dt for the DateTime API. You can find it here.

Using with this class is very easy:

$t = '2 листопада 2020, 21:00, п’ятниця';

$ok = dt::setDefaultLanguage('uk_UA');
$dt = dt::createDtFromFormat('j F Y, H:i, *', $t);

echo $dt; //2020-11-02 21:00:00
Related