user3253002
user3253002

Reputation: 1671

Laravel: How to deal with dates in different timezones

A lot of questions have been asked about this subject. The best answer that I found is this one: How to set local timezone in laravel So the main rule is to keep all database entries in the same timezone.

But I have a specific case where this answer does not work for me. For some models, I have only a date (no datestamp). Example: suppose that I only store the date of when this question was asked (= 2018-01-25). However in Europe it is already 2018-01-26. Someone has a solution for this?

Changing my date field to a datestamp? What with existing dates?

Upvotes: 1

Views: 2897

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

If you're only talking about a date, then there is no time component and thus time zones are irrelevant. For this reason, most platforms do not have a separate date-with-zone type.

You're correct that not every time zone experiences the same date at all times, and that the start of a date and the end of the date occur at different times in different time zones. However, did you notice that in the prior sentence that I had to use the word "time" to rationalize about these points? :-)

Because date and time zone don't come together without time, there's no purpose in keeping them in the same field. Instead, keep two fields in your model - one for the date, and one for the time zone. In many cases, you may even find they belong in two different models.

As a use case example, consider birthdays. Mine is 1976-08-27. That's all it is - just a date. The time zone of my birth is irrelevant, and so is the time zone I'm located in - until I want to evaluate whether it's currently my birthday (or how long until my birthday, etc.) For those operations, my current time zone is important, and so is the start time-of-day and end time-of-day of that time zone. Thus - two different fields.

Upvotes: 1

Bogdan Kyrychuk
Bogdan Kyrychuk

Reputation: 307

You can use this library jamesmills/laravel-timezone

OR

If you need custom configuration:

  1. Configure your app timezone to UTC.

    'timezone' => 'UTC',

  2. You can store different timezones in database column.

  3. When outputting/displaying dates, just format it to use that timezone.

    $timezone = 'America/Vancouver';
    $model->created_at->setTimezone($timezone);

created_at and updated_at are automatically converted to carbon instances, which makes this easier. If you have other dates that you're using, add them to the protected $dates array on the model and laravel will convert them to carbon instance too. Then you can use carbons setTimezone() to change the date/time to the timezone.

Upvotes: 4

Related Questions