简体   繁体   中英

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?

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")

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM