Date format issue fix
April 10, 2025 · AI Conversations
CakeI18nFrozenTime::setToStringFormat( $format ); // For any immutable DateTime
CakeI18nFrozenDate::setToStringFormat( $format );
Without adding above
date('d-m-Y', strtotime($item['created']))
This showing 01-01-1970
date('d-m-Y', strtotime($item['created']))
is that `$item['created']` is **not** being interpreted correctly by `strtotime()`. Likely, it’s a `FrozenTime` or `FrozenDate` object and not a string.
Here's what's happening:
– `strtotime()` expects a **string**, but `$item['created']` is an object.
– `strtotime(object)` returns `false`, and `date()` then converts `false` to `0`, resulting in the Unix epoch date: `01-01-1970`.
—
### ✅ Proper Fix
You don’t need `strtotime()` here. Instead, just use:
echo $item['created']->format('d-m-Y');
If `$item['created']` is an instance of `CakeI18nFrozenTime` or `FrozenDate`, it supports the `format()` method directly.
—
### 🔧 Optional (Global Formatting)
If you want to **globally** change the default string format (e.g., when casting to string or JSON), use:
use CakeI18nFrozenTime;
use CakeI18nFrozenDate;
$format = 'd-m-Y';
FrozenTime::setToStringFormat($format);
FrozenDate::setToStringFormat($format);
Make sure this is placed in your `AppController::initialize()` or in a bootstrap file where it runs **before rendering any view**.
—
### Summary
| Code | Output |
|——————————|—————————————-|
| `date('d-m-Y', strtotime($item['created']))` | ❌ Incorrect (`01-01-1970`) |
| `$item['created']->format('d-m-Y')` | ✅ Correct formatted date |
| `FrozenTime::setToStringFormat()` | ✅ Global formatting |
Let me know if you want to apply this format in JSON responses or views too.