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?
Asked
Active
Viewed 6,950 times
6

Murcielago
- 1,030
- 1
- 14
- 24
2 Answers
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
-
Per @larskris's response, where you link to in the docs, it does say "currently it only supports “Etc/UTC” as time zone". – Murcielago Jul 30 '18 at 19:14
-
I edited the response to make it more clear that a timezone database can be specified. – Mario Olivio Flores Mar 18 '21 at 12:28