when trying to parse a date-time (Zulu) with Carbon, I get the following error:
$t = '2021-06-01T21:29:55.155257426Z';
$r = Carbon::parse($t)->setTimezone('UTC');
dd($r);
Could not parse '2021-06-01T21:29:55.155257426Z': DateTime::__construct(): Failed to parse time string (2021-06-01T21:29:55.155257426Z) at position 0 (2): The timezone could not be found in the database
However, if I remove the last 3 digits, everything works fine, e.g.:
$t = '2021-06-01T21:29:55.155257Z';
$r = Carbon::parse($t)->toDateTimeString('microsecond');
dd($r);
"2021-06-01 21:29:55.155257"
I'm not sure what to do to parse the microseconds when I have 9 digits (.155257426Z). Any help is appreciated. Thank you.
PHP's DateTime, which underpins Carbon, can only handle fractional seconds up to six digits.
The following will trim it down to six at most:
function trim_nanoseconds($t) {
return preg_replace_callback(
'/\.(\d+)(.*)$/',
function($a){
return sprintf('.%s%s', substr($a[1], 0, 6), $a[2]);
},
$t
);
}
$t = '2021-06-01T21:29:55.123456789Z';
var_dump(fix_nanoseconds($t));
Output:
string(27) "2021-06-01T21:29:55.123456Z"