Skip to content

Commit 517dcf9

Browse files
committed
Added README notice about assigning carbon instances to casted attributes
1 parent 840f727 commit 517dcf9

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,35 @@ $date = Timezone::store(new Carbon('2023-01-01 00:00:00', 'Europe/Brussels'));
9494
// Alternatively, set the storage timezone yourself:
9595
$date = (new Carbon('2023-01-01 00:00:00', 'Europe/Brussels'))->setTimezone(Timezone::storage());
9696
```
97+
98+
## Assigning values to casted attributes
99+
100+
Many developers are used to assign Carbon instances to date attributes:
101+
102+
```php
103+
$model->published_at = Carbon::create($request->published_at);
104+
```
105+
106+
**This can lead to unexpected behavior** because the assigned Carbon instance will default to the `UTC` timezone, wheras the provided value was probably meant for another timezone. The datetime string will be stored as-is without shifting its timezone accordingly first.
107+
108+
In order to prevent this, it is recommended to let the Cast do the heavy lifting:
109+
110+
```php
111+
$model->published_at = $request->published_at;
112+
```
113+
114+
The package will now treat the provided datetime string using the correct Timezone (for instance, `Europe/Brussels`) and store the shifted `UTC` value in the database correctly.
115+
116+
A more verbose (but also correct) method would be to create the Carbon instance using the `Timezone` facade :
117+
118+
```php
119+
$model->published_at = Carbon::create($request->published_at, Timezone::current());
120+
// Or, shorthand:
121+
$model->published_at = Timezone::date($request->published_at);
122+
```
123+
124+
**This is not a bug**, it is intended behavior since one should be fully aware of the Carbon instance's timezone before assigning it.
125+
97126
## 🔥 Sponsorships
98127

99128
If you are reliant on this package in your production applications, consider [sponsoring us](https://github.com/sponsors/whitecube)! It is the best way to help us keep doing what we love to do: making great open source software.

0 commit comments

Comments
 (0)