Kevin McDonough
Kevin McDonough

Reputation: 68

Elixir equivalent for Ruby on Rails time helpers (e.g. 1.day.ago)

I am currently building a Phoenix app and am relatively new to the ecosystem. Having come from Ruby on Rails, I'm quite used to the convenience date/time methods available in rails (through the builtin ActiveSupport Gem I believe). For example:

1.day.ago
some_date_time + 1.hour
some_date.next_weekday.at_beginning_of_day

I especially appreciate their ability to clearly & concisely express conceptually simple (to humans at least) time operations, while abstracting away the messy date math.

I find the following objectionable

NaiveDateTime.add(
  NaiveDateTime.utc_now(),
  Enum.random(-5..-1) * 60 * 60 * 24)

It's not immediately clear & won't handle subtle time caveats like leap seconds/days etc. It's also not immediately clear how I might move forward 1 month or year.

Is there a popular/canon Elixir package that provides similar clarity & power? Bonus points if it's also concise.

Upvotes: 1

Views: 253

Answers (1)

zwippie
zwippie

Reputation: 15515

Well, there is timex, probably the most used elixir time-related library. I don't think it has all the bells and whistles Rails has but it should make live a bit easier. Some examples from the timex readme:

> use Timex
> datetime = Timex.now
#<DateTime(2016-02-29T12:30:30.120+00:00Z Etc/UTC)
> Timex.shift(datetime, hours: 2, minutes: 13)
#<DateTime(2016-02-29T14:43:30.120Z Etc/UTC)>

Upvotes: 2

Related Questions