用凤凰格式化时间

Formatting time ago in words with phoenix

我正在尝试将模板中的时间格式化为“12 秒前”或“14 分钟前”。 Ecto 目前吐出看起来像 2016-06-28 21:35:21.

的超时

目前我只是这样渲染时间:<p><%= post.inserted_at %></p>

我知道 ruby/rails 有一个名为 time_ago_in_words() 的函数可以满足我的需求。也许这可以通过新的 Elixir 1.3 日历类​​型来完成?

您可以使用 Timex 十六进制包。特别是 from_now 函数。您需要确保您拥有 DateTime 类型的日期。然后只需使用

Timex.from_now(my_date)
#"2 hours ago"

要将 Ecto.DateTime 转换为 Timex.DateTime 我使用了这个

my_ecto_dateTime
#Ecto.DateTime<2016-05-16T16:26:55Z>
{:ok, date} =  Ecto.DateTime.dump(my_ecto_dateTime)
my_date = Timex.DateTime.from date

Here is a port from Rails

time_ago_in_words(~N[2015-03-05 21:45:00])
"about 6 years"

distance_of_time_in_words(~N[2004-06-06 21:45:00], ~N[2004-06-06 21:45:00], include_seconds: true)
"less than 5 seconds"

distance_of_time_in_words(~N[2004-06-06 21:45:00], ~N[2004-06-06 21:45:00])                       
"less than a minute"