How do I convert another language date format to English language format (Y-m-d)?

Viewed 310

I am scraping a blog site, until now everything was working fine, but now that the blog site has changed to multi language, now I have a problem scraping the date and time. So help me fix that.

Earlier I used to get the date format from the blog site in different ways as follows.

Thursday, 31 October 2019
Thursday, September 10, 2020

That worked fine for me, as I could convert to PHP in the following ways.

$fetched_date = $info['date']; // which is 'Thursday, 31 October 2019'
$time_stamp = strtotime($fetched_date);

$new_date = date('Y-m-d', $time_stamp); 
// It was gave me this date '2019-10-31',
// which is perfect for me, because i can store it to my DB.

But since the blog site has changed to multi-language, I occasionally get a date in another language as follow. So how do I convert it?

गुरुवार, १८ जून, २०२० // mr_IN
ગુરુવાર, 10 સપ્ટેમ્બર, 2020 // gu_IN

So when I try with this date format, it gives me the wrong date, which I can't even use. like,

$fetched_date = $info['date']; // which is 'गुरुवार, १८ जून, २०२०'
$time_stamp = strtotime($fetched_date);

$new_date = date('Y-m-d', $time_stamp); 
// It was gave me this date '1970-01-01', which is wrong and i can't store to my DB.
// it should be "2020-06-18"

And when I do scraping I also get a language code like: mr_IN, gu_IN , so how do I get the correct date using that language code? I want to convert the date in PHP and store it in MySQL, how do I do that?

1 Answers

The IntlDateFormatter class can help here. However, the date format must fit.

$dateString = 'गुरुवार, १८ जून, २०२०';

$timeZone = new DateTimeZone("UTC");
$fmt = new IntlDateFormatter(
    'mr_IN',
    IntlDateFormatter::FULL,
    IntlDateFormatter::NONE,
    $timeZone,
    IntlDateFormatter::GREGORIAN
);

$ts = $fmt->parse($dateString);
$dateTime = date_create("today",$timeZone)->setTimeStamp($ts);

echo $dateTime->format("Y-m-d");  //2020-06-18
Related