6

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?

Murcielago
  • 1,030
  • 1
  • 14
  • 24

2 Answers2

10

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")
Mario Olivio Flores
  • 2,395
  • 1
  • 20
  • 19
larskris
  • 198
  • 1
  • 2
  • 8
  • 6
    `Timex` is not an Elixir core in the first place and you should at least mention that for this to work the `timex` package should be included into the list of `deps`. – Aleksei Matiushkin Jul 31 '18 at 04:25
7

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")
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56