Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martijnvreeken's avatar

Weird Carbon behaviour

Hi, Consider this tinker code:

>>> $dates = \json_decode('["25-02-2022 00:00", "13-05-2022 00:00", "03-06-2022 00:00"]')
=> [
     "25-02-2022 00:00",
     "13-05-2022 00:00",
     "03-06-2022 00:00",
   ]
>>> collect($dates)
=> Illuminate\Support\Collection {#4500
     all: [
       "25-02-2022 00:00",
       "13-05-2022 00:00",
       "03-06-2022 00:00",
     ],
   }
>>> collect($dates)->mapInto(\Carbon\Carbon::class)
=> Illuminate\Support\Collection {#4591
     all: [
       Carbon\Carbon @1645747200 {#4644
         date: 2022-02-25 00:00:00.0 +00:00,
       },
       Carbon\Carbon @1652396400 {#4647
         date: 2022-05-13 00:00:00.0 +01:00,
       },
       Carbon\Carbon @1654207200 {#4646
         date: 2022-06-03 00:00:00.0 +02:00,
       },
     ],
   }

See how Carbon adds the +01:00 and +02:00 there? That's not in the strings as you can see. Anyone have any explanation for this behaviour?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

The problem is mapInto passes the array (collection) key into the constructor as the second argument (which Carbon sees as the TZ offset)!

public function mapInto($class)
    {
        return $this->map(function ($value, $key) use ($class) {
            return new $class($value, $key);
        });
    }

Instead:

collect($dates)->map(fn ($date) => \Carbon\Carbon::parse($date));
2 likes
martijnvreeken's avatar

@tykus Ah, well spotted! Thanks. I changed my code to use a simple ->map() and this works as expected.

Please or to participate in this conversation.