datetimeelixirtimex

set datetime milliseconds precision - elixir


I am trying to get a datetime which has only 3 digits in the sub-second part.
Using timex I get the following result:

iex(12)>   {:ok, date} = Timex.format(Timex.shift(Timex.local, days: 16), "{ISO:Extended}")
{:ok, "2017-04-22T09:00:44.403879+03:00"}

How can I get something like this:
{:ok, "2017-04-22T09:00:44.403+03:00"} ?


Solution

  • DateTime has a microsecond field which is a tuple containing the value and precision. If you change the precision to 3, you'll get 3 digits in the microsecond output. I couldn't find any function in Timex which does this, but you can modify the value manually:

    iex(1)> dt = %{microsecond: {us, precision}} = Timex.now
    #<DateTime(2017-04-06T08:26:24.041004Z Etc/UTC)>
    iex(2)> precision
    6
    iex(3)> dt2 = %{dt | microsecond: {us, 3}}
    #<DateTime(2017-04-06T08:26:24.041Z Etc/UTC)>
    iex(4)> dt2 |> Timex.format!("{ISO:Extended}")
    "2017-04-06T08:26:24.041+00:00"