Murcielago
Murcielago

Reputation: 1182

Elixir add timezone data to naive date time

I have a NaiveDateTime that I need to add timezone data to. For example if I have a naive_date value like ~N[2015-10-03 12:00:00.000000] and I want set it to "America/Los_Angeles" timezone, how is that possible in Elixir?

Upvotes: 7

Views: 7895

Answers (2)

larskris
larskris

Reputation: 306

Using Timex Package, one could:

Update: better solution

iex> use timex

iex> naive_date = ~N[2015-10-03 12:00:00.000000]

iex> Timex.to_datetime(naive_date, "America/Los_Angeles")
#DateTime<2015-10-03 12:00:00-07:00 PDT America/Los_Angeles>

Old solution

use timex

utc_time = DateTime.from_naive!(~N[2015-10-03 12:00:00.000000], "Etc/UTC")

tz_offset =
  Timex.timezone("America/Los_Angeles", utc_time)
  |> Timex.Timezone.total_offset()

Timex.shift(utc_time, seconds: -tz_offset)
  |> Timezone.convert("America/Los_Angeles")

Upvotes: 10

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

According the the NaiveDateTime documentation:

We call them "naive" because this datetime representation does not have a time zone.

That means you can't add timezone data to a NaiveDateTime object.


However you can convert a NaiveDateTime to a DateTime that can hold time zone data with DateTime.from_naive!/2:

DateTime.from_naive!(~N[2015-10-03 12:00:00.000000], "Etc/UTC")

Upvotes: 9

Related Questions