Eloquent Carbon and displaying dates in a users local timezone

Posted 3 years ago by robjbrain

I want to be able to display dates in the users local timezone, so if someone submits a comment in the UK at 2pm someone viewing that comment in Italy will see the time showing as 3pm. If the Italian user then submitted a reply 5 minutes later it would show as 3.05pm for him and 2.05pm for the user in the UK... fairly elementary.

I have the users timezone saved in the database accessible via Auth::user()->timezone

In the past I always saved dates as integer timestamps in the database and used date_default_timezone_set() when getting the user object and then date(d-m-Y H:i:s, $model->timestamp) would display in the users local timezone.

But now that i've tried to follow Laravel "standard" practice, use carbon and save as timestamps in the DB, I can't figure out how to get the date displaying relative to the users local timezone.

So lets say I have a model with the timestamp saved in the database like this: "2015-10-17 13:56:26"

I am using date mutators in Eloquent so this column will be converted to a carbon instance.

Now if I use:


$model->timestamp->format('d-m-Y H:i:s')

It will always display the exact same date, exactly what it says in the database, no matter what was set in the timezone.

But it does have an effect when saving dates e.g.


This will save the date in the database itself as 3pm for the Italian and 2pm for the guy in the UK, even when they're both saving at the exact same time. This is exactly the opposite of what I wanted!!!! If I did this I would be saving dates in the database in all kinds of different timezones, horrendous, I definitely want to avoid that.

I've given a bit of detail in the hope someone will see my current train of thought and tell me why i'm being an idiot, but the question is simple:

Using Eloquent Date Mutators and Carbon, how can I save all dates in the database in Europe/London time, but whenever i'm displaying dates use a custom timezone set in the Users model?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.