Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

datetime - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...