Home > database >  Carbon PHP parse datetime with dot notation
Carbon PHP parse datetime with dot notation

Time:01-13

I'm using Carbon 2 and am having an issue with some strange dates in my application that are given to me by a third party api, ideally they'd always be in the YYYY-MM-DD format but a few are coming in the following format: YYYY.MM.DD.

How can I use Carbon::parse() or PHP to reliably convert the string to hyphens and then parse it if in that format?

Example:

echo Carbon::parse('2022.07.24 10:34:05');

This is invalid.

Maybe I just look for the dots and change to hyphen and try re-parsing?

CodePudding user response:

As described in the documentation:

$date = Carbon::createFromFormat('Y.m.d H:i:s', '2022.07.24 10:34:05');

CodePudding user response:

In your case, you can normalize the string before the parse():

$str = '2022.07.24 10:34:05'; // or '2022-07-24 10:34:05'
echo Carbon::parse(strtr($str, ['.' => '-']));
  •  Tags:  
  • Related