Santosh Achari
Santosh Achari

Reputation: 3006

Laravel Multiple Timezones

I am trying build a database of user trips, which involves storing:

Note, that both the airports can be in different timezones. I need to work out the time difference, and number of days to this flight etc.

I am not sure how to approach this problem. Should I add more columns to store local date time, and UTC times?

Also, I have seen that Laravel has dateTimeTz() column type. However it doesn't seem to be storing any information about timezone?

Posts Table:

$table->dateTimeTz('newTime')->nullable();

Setting new time:

$p->newTime = \Carbon\Carbon::now('Asia/Kolkata')
=> Carbon\Carbon {#841
     +"date": "2017-03-28 16:23:33.490926",
     +"timezone_type": 3,
     +"timezone": "Asia/Kolkata",
   }

>>> $p
=> App\Post {#836
     id: 1,
     user_id: 1,
     title: "Et quaerat deserunt qui ullam voluptas.",
     body: "Aut eos id ut qui laborum. Tempore rerum ut quas deserunt voluptas optio.",
     slug: "et-quaerat-deserunt-qui-ullam-voluptas",
     newTime: "2017-03-28 16:23:33",
     created_at: "2017-03-28 10:51:36",
     updated_at: "2017-03-28 10:51:36",
   }

Upvotes: 2

Views: 4179

Answers (2)

Emad Adly
Emad Adly

Reputation: 1475

is quite simple follow it:

  • Store all timestamps in UTC (default in laravel config).
  • The users can select their timezone and save it in the user table.
  • Then you can use carbon to convert dates to their local time. (Carbon library, which is inside of Laravel already ).

For example, for a user who lives in different country like Europe/London or Asia/Kolkata

$something->created_at->timezone($user->timezone);

Upvotes: 8

Alexey Torochkov
Alexey Torochkov

Reputation: 171

Easiest way is to store date and time in UNIX timestamp (it's timezone independent). Then you can convert it to any timezone (depends on user location or airport timezone)

Upvotes: 2

Related Questions