rai
rai

Reputation: 229

Carbon - Dates are in ISO8601 format with offset notation

I need to convert a user given datetime with format Y-m-d H:i:s to ISO8601 format with offset notation using Php Carbon . The required timezone is Europe/Berlin.

What I have tried so far is

     $from = '2021-05-01 00:00:00';
     $dateF = Carbon::createFromDate($from)->tz('Europe/Berlin')->format('Y-m-d\Th:i:sP');

And I got the result which is almost what I wanted

     2021-05-01T02:00:00+02:00

What I actually need is the accurate h:i:s

     2021-05-01T00:00:00+02:00

Any Ideas ?

Upvotes: 2

Views: 1719

Answers (1)

KyleK
KyleK

Reputation: 5121

Be careful you need H instead of h for 0-23 hour. And you just have to use parse and include the timezone of your date in it to make Carbon aware of the timezone in which the date-time must be read:

$from = '2021-05-01 00:00:00';
echo Carbon::parse("$from Europe/Berlin")->format('Y-m-d\TH:i:sP');

createFromDate is not good if you care about the hour/minute/second in your $from variable, as it returns only the date you pass with current time.

Upvotes: 2

Related Questions