Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Murcielago Avatar asked Jul 30 '18 18:07

Murcielago


People also ask

How do I make datetime timezone aware?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

What does timezone naive mean?

Timezone-Aware datetime object: does have a timezone associated with it. Timezone-Naïve datetime object: does not have any timezone associated with it. Rules of thumb. Always work with "timezone-aware" datetime objects. Always store datetime in UTC and leave rendering of timezones to the front-end.

What is naive Date Time?

They are called “naive” because they don't have a time zone associated with them. This means the date may not actually exist in some areas in the world, even though they are “valid”. For example, when daylight saving changes are applied the clock typically moves forward or backward by one hour.

How do you get a timestamp in Elixir?

You can also use :os. timestamp\0 , which returns {megaseconds, seconds, microseconds} from UTC. :os. timestamp |> :calendar. now_to_datetime will give you now in erlang standard {{YYYY, MM, DD}, {HH, MM, SS}} format.


2 Answers

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")
like image 85
larskris Avatar answered Sep 21 '22 17:09

larskris


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")
like image 44
Ronan Boiteau Avatar answered Sep 19 '22 17:09

Ronan Boiteau