Mitkins
Mitkins

Reputation: 4351

Ecto.DateTime and Time Zones

Is there any way to adjust Ecto.DateTime objects for a timezone? I'd like to read an Ecto.DateTime from the database, but then adjust it for a user nominated timezone?

Also, I'd like to accept data entry and convert it back, using the timezone setting.

I've been looking for a library or a technique to do this but haven't found anything obvious

Upvotes: 4

Views: 2024

Answers (1)

Dogbert
Dogbert

Reputation: 222398

Ecto doesn't include any such functions. There are several libraries for Elixir available which can do this. I've only used timex. To store Timex values in the database using Ecto, you can use the timex_ecto package. Here's how you would change the timezone of a Timex.DateTime value to America/Los_Angeles:

iex(1)> original = Timex.now
#<DateTime(2016-08-17T06:24:03.015339Z Etc/UTC)>
iex(2)> timezone = Timex.Timezone.get("America/Los_Angeles", original)
#<TimezoneInfo(America/Los_Angeles - PDT (-07:00:00))>
iex(3)> converted = Timex.Timezone.convert(original, timezone)
#<DateTime(2016-08-16T23:24:03.015339-07:00 America/Los_Angeles)>
iex(4)> Timex.format!(original, "{ISO:Extended}")
"2016-08-17T06:24:03.015339+00:00"
iex(5)> Timex.format!(converted, "{ISO:Extended}")
"2016-08-16T23:24:03.015339-07:00"

Upvotes: 5

Related Questions