为 time_ago_in_words 自定义 I18n

Customize I18n for time_ago_in_words

我使用 time_ago_in_words 作为未来和过去的时间戳。

这是我的 en.yml 的样子:

datetime:
  distance_in_words:
    x_days:
      one:   "1 day"
      other: "%{count} days"

如果时间戳不是未来的,我想打印 "yesterday" 而不是“1 天”。

这可能吗?

简短的回答是否定的,time_ago_in_words 只需调用 distance_of_time_in_wordsto_time 参数设置为 Time.now

编辑:为了可读性。

长答案(在评论中讨论):可以使用 distance_of_time_in_words 设置 :scope 选项来使用您的翻译而不是默认翻译。不过,明天和昨天距离现在还有“1 天”,因此有必要将其包装在一个自定义方法中,以不同方式处理过去和未来的日期。