#Cast DateTime

14 messages · Page 1 of 1 (latest)

dusky lynx
#

hello, I'm working with time, and my cast outputs a different value than what's in the database.

protected $casts = [
        'created_at' => 'datetime:Y-m-d h:i:s',
        'deleted_at' => 'datetime:Y-m-d h:i:s'
];
show: 2022-11-18 09:39:53 - database: 2022-11-18 18:39:53
show: 2022-11-17 09:15:27 - database: 2022-11-17 18:15:27
show: 2022-11-17 12:15:27 - database: 2022-11-17 09:15:27
merry solstice
#

Why are you casting dates and times in the first place? Lowercase h is also going to give you 12-hour times instead of 24-hour times. Which is a good reason why you shouldn’t be dicking about with the format in the first place.

dusky lynx
merry solstice
#

Remove the cast.

#

Stop messing with it.

#

I’m guessing you’ve changed your app’s timezone in your config/app.php file, too…

#

Since 18 − 12 ≠ 09

merry solstice
#

Again, leave it as UTC.

#

All of these changes are just compounding, hence odds values.

#

You’re juggling timezones and (incorrect) casts, and then acting confused as to why you’re getting incorrect values.

#

You should be storing all dates and times as UTC in your database. You can then convert the timezone and format on the front-end if you really need to:

{{ $foo->created_at->toFormattedDateString() }}
#

If you want to display dates and times in a different format, then use an accessor for that. Don’t try adding casts to the columns.