Carbon parse date format
Asked Answered
I

1

10

I'm trying to parse a date formated like :

2017-09-20T10:59:10.0000000 01:00

I'm using Carbon, so i tried :

Carbon::createFromFormat('Y-m-dTH:i:s.u vP', $date)

Which output :

The timezone could not be found in the database\n
Unexpected data found.\n
Data missing

I guess the last timezone argument maybe wrong but i couldn't find how to parse that date format :/

Thanks for help !

Inspirit answered 27/2, 2018 at 10:9 Comment(0)
C
11

You'll need to add a sign to the timezone, for example:

+01:00

Then this will work for you:

Carbon::createFromFormat('Y-m-d\TH:i:s.0000000 P', $date)

If your string can have -01:00 but instead of +01:00 you're getting 01:00, do this first:

$timezone = str_after($date, ' ');
if ($timezone[0] !== '-') {
    $date = str_before($date, ' ') . ' +' . $timezone;
}
Cumulus answered 27/2, 2018 at 10:15 Comment(4)
Thanks for help, it works ;) There is no way to parse the date without modifying the string ? It's returned by third party service APIInspirit
@LouisRocher there is a way but it's more verbose. I'd use this one. You can use another variable to save the original string if you need it for some reason.Cumulus
There is a problem... It give no errors but the date is wrong : 1970-01-01 :/ I finally use Carbon::createFromFormat('Y-m-d\TH:i:s+', $date) to ignore what's after 2017-09-20T10:59:10. Thanks for help !Inspirit
@LouisRocher it's because of .0000000. Usually, APIs always return zeros, so you can skip those. I've updated the code if you'll want an alternative.Cumulus

© 2022 - 2024 — McMap. All rights reserved.