简体   繁体   中英

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

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

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>

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"

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