3

I'm sure there is a already a solution for what I need, but I guess I don't know what to search for. Any pointings into the right direction?

I'm thinking of something like Rails' distance_of_time_in_words_to_now.

Thank you.

4

3 回答 3

10

我相信你可以使用这样的助手。

def custom_format(date)
  if date == Date.today
    "Today"
  elsif date == Date.yesterday
    "Yesterday"
  elsif (date > Date.today - 7) && (date < Date.yesterday)
    date.strftime("%A")
  else
    date.strftime("%B %-d")
  end
end

没有测试代码,它只是指向您的问题的指针。

于 2012-12-19T10:35:52.217 回答
5

创建一个文件 .../config/initializers/time_format.rb 并将此代码放入其中:

Time::DATE_FORMATS[:humanized_ago]  = ->(time) do
  st = Time.now.beginning_of_day
  nd = Time.now.end_of_day

  case 
  when time.between?(st + 1.day, nd + 1.day)
    "Tomorrow #{time.strftime('%H:%M')}"
  when time.between?(st, nd)
    "Today #{time.strftime('%H:%M')}"
  when time.between?(st - 1.day, nd - 1.day)
    "Yesterday #{time.strftime('%H:%M')}"
  when time.between?(st - 6.day, nd - 2.day)
    time.strftime('%a %H:%M')
  else 
    time.strftime('%y-%b-%d %H:%M')
  end
end

在 Rails Time 对象上,调用 function time.to_s(:humanized_ago)。如果你不喜欢符号“:humanized_ago”,可以在 time_format.rb 的第一行随意更改它。”如果你想要其他格式,你可以弄清楚。

我按照我的方式写比较是有原因的。我找不到使用 Ruby 内置范围来测试时间的方法,并且您需要能够测试不包括终点的时间间隔。

于 2014-01-16T00:10:12.920 回答
1

尝试这个

<%= time_ago_in_words(time) %> ago
于 2012-12-19T10:36:15.090 回答