Today I Learned

hashrocket A Hashrocket project

Compare NaiveDateTimes by a specific unit

In Elixir, you can get the difference between two NaiveDateTimes using the NaiveDateTime.diff/3 function.

The third arg allows you to pass a unit such as :microsecond, :millisecond, or any unit returned from System.time_unit. By default, the unit is set to :second.

NaiveDateTime.diff(~N[2014-10-02 00:29:18], ~N[2014-10-02 00:29:10])
#=> 8
NaiveDateTime.diff(~N[2014-10-04 00:29:18], ~N[2014-10-02 00:29:10], :day)
#=> 2

Interestingly enough :day works as a unit, but not :month, or :year. 🤔

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.