Hi:

Thank you, Elixir community, for building this incredible language and 
ecosystem!

I just had a need to truncate a NaiveDateTime to the nearest minute and was 
surprised to see that option isn't available.

I'd like to propose something like the following (which I just typed out 
but haven't tested):

```
  @doc """
  Returns the given naive datetime truncated to the given precision
  (`:microsecond`, `:millisecond`, `:second`, `:minute` or `:hour`).

  The given naive datetime is returned unchanged if it already has lower 
precision
  than the given precision.

  ## Examples

      iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], 
:microsecond)
      ~N[2017-11-06 00:23:51.123456]

      iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], 
:millisecond)
      ~N[2017-11-06 00:23:51.123]

      iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :second)
      ~N[2017-11-06 00:23:51]

      iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :minute)
      ~N[2017-11-06 00:23:00]

      iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :hour)
      ~N[2017-11-06 00:00:00]

  """
  @doc since: "1.6.0"
  @spec truncate(t(), :microsecond | :millisecond | :second | :minute | 
:hour) :: t()
  def truncate(%NaiveDateTime{microsecond: microsecond} = naive_datetime, 
:hour) do
    %{naive_datetime | minute: 0, second: 0, microsecond: 
Calendar.truncate(microsecond, :second)}
  end

  def truncate(%NaiveDateTime{microsecond: microsecond} = naive_datetime, 
:minute) do
    %{naive_datetime | second: 0, microsecond: 
Calendar.truncate(microsecond, :second)}
  end

  def truncate(%NaiveDateTime{microsecond: microsecond} = naive_datetime, 
precision) do
    %{naive_datetime | microsecond: Calendar.truncate(microsecond, 
precision)}
  end
```

Thank you for considering this idea.

Cheers,

James Lavin

-- 
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-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/19ac16f9-7f73-4b62-9ea8-8c91e1f14838n%40googlegroups.com.

Reply via email to