[Proposal] `Duration.to_float/2`

42 views
Skip to first unread message

Wígny Almeida

unread,
May 26, 2024, 2:02:32 AMMay 26
to elixir-lang-core
Following the recent proposals and work done around the new `Duration` API, I wanted to propose having a function available for converting a `Duration` into a specific time unit, returning a float value.

I see this function being useful where in your system you want to work with durations, but on inputs and outputs, you are required to convert this duration into a more plain value. The examples I can think of are 1) having an Ecto custom type that loads a value in seconds (or another unit) from the database, converting it into a duration using `Duration.new!(second: value)` and dumps a duration again into a value in seconds by calling `Duration.to_float(duration, :second)` and 2) transforming a duration into a plain number in Phoenix HTML inputs.

Examples of similar APIs I could find are in the JavaScript Temporal.Duration API or Ruby ActiveSupport::Duration.

One challenge we may encounter when implementing this function is calculating, for example, how many seconds there are in a year. For this, I think we can rely on the Calendar APIs? 

Thoughts?



José Valim

unread,
May 26, 2024, 3:53:21 AMMay 26
to elixir-l...@googlegroups.com
We have Kernel.to_timeout, which returns this in milliseconds, but we don't have a general API. The implementation raises if the duration has months or years in it, because it is impossible to convert it to an absolute value without having a reference datetime attached to it. In such cases, you can achieve what you want using "DateTime.diff(DateTime.shift(dt, duration), dt)", so there is probably not a big reason for exposing an API for this.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/f11b73c0-b709-4fbe-94fe-f76412f7a14cn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages