简体   繁体   中英

How to get standardised date/time from abbreviated non-English format in PHP?

I have an input date string of something like Sett21 , which is in Italian, and I need to get a standardized format such as 01/09/2021.

Is there a way to create a date from an abbreviated non-English string? I'm attempting to use Carbon and it can handle a date string abbreviated in English fine:

$date = Carbon::create("Sept2021");

Output: Wednesday, September 1, 2021 12:00 AM

However it fails the Italian abbreviated month Sett .

Solution via an array with the Italian month names as in CBroe's comment.

$input = 'Sett21';

$list = 'genn,febbr,mar,apr,magg,giugno,luglio,ag,sett,ott,nov,dic';
foreach(explode(',',$list) as $key => $month){
  $in = preg_replace('~'.$month.'~iu',($key+1)." ",$input);
  if($in !== $input) break;
}

$date = Carbon::createFromFormat('!m y',$in);
echo $date;
//or
$dateTime = DateTime::createFromFormat('!m y',$in);
echo "\n";
echo $dateTime->format('Y-m-d H:i:s');

Output:

2021-09-01 00:00:00
2021-09-01 00:00:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM