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?
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.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With