phplaravelphp-carbon

Why formatted date with carbon is invalid?


Why in In laravel 11, PHP 8.2 app running code

$minDay = CurrencyHistory::select(DB::raw('MIN(day) as min_day'))->first()->min_day;
\Log::info($minDay);
\Log::info(Carbon::createFromTimestamp(strtotime($minDay))->format('j F, Y'));

I see results :

[2024-10-05 07:30:08] local.INFO: 2024-09-28
[2024-10-05 07:30:08] local.INFO: 27 September, 2024

So the min day is 2024-09-28, but resulting value on a form I have is 27 September, 2024

In CurrencyHistory Model I have :

protected $casts = [
        'created_at' => 'datetime', 'updated_at' => 'datetime', 'value' => HistoryMoney::class, 'day' => 'date'
    ];

Tracing SQL I have :

   SELECT MIN(day)     AS min_day
    FROM `currency_histories` limit 1

Which returns value 2024-09-28.

Is format 'j F, Y' invalid? With format format('d F, Y' the same result... Which format have I to use?


Solution

  • This is a common missatke.

    When you use Carbon::createFromTimestamp(strtotime($minDay)), a Carbon instance is created using your default timezone. If your timezone is behind UTC, the time goes backward, resulting in a date of 2024-09-27.

    Update like this

    $minDay = CurrencyHistory::select(DB::raw('MIN(day) as min_day'))->first()->min_day;
    
    # Use Carbon::parse
    $formattedDate = Carbon::parse($minDay)->format('j F, Y');