set datetime milliseconds precision - elixir

5.6k views Asked by At

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"} ?

2

There are 2 answers

3
Dogbert On BEST ANSWER

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"
0
Alexandre L Telles On

Since Elixir 1.6.0 there is now the truncate/2 function present on modules Time, DateTime and NativeDateTime for this.

Here is an example using DateTime.truncate/2

iex(1)> dt = Timex.now()
#DateTime<2018-02-16 19:03:51.430946Z>

iex(2)> dt2 = DateTime.truncate(dt, :millisecond)
#DateTime<2018-02-16 19:03:51.430Z>