12

除了“time_ago_in_words”之外,rails 中是否有不同的时间计算?我希望能够只使用 'h' 几个小时 'd' 天 'm' 几个月......例如。3d,或 4h,或 5m

我的代码现在...

<%= time_ago_in_words(feed_item.created_at) %> ago.
4

3 回答 3

17

构成此字符串的组件可以本地化,并且位于 datetime.distance_in_words 命名空间中

例如棍子

en:
  datetime:
    distance_in_words:
      x_minutes:
        one: "1m"
        other: "%{count}m"

轨道会说 10m 而不是 10 分钟。根据需要重复数小时、数天等。您可以在 action_view 中检查locales/en.yml以获取所有键。

如果您只想要短格式,您可以创建一个仅使用这些键的伪语言环境并像这样使用它

time_ago_in_words created_at, false, :locale => :en_abbrev
于 2012-09-26T08:34:45.343 回答
2

在较新版本的 rails 中,您可以将范围指定为方法的选项,如下所示:

time_ago_in_words(company.updated_at, scope: 'datetime.distance_in_words.abbrv')

然后你只需要像这样构造你的常规 i18n 文件:

en:
  datetime:
    distance_in_words:
      abbrv:
        about_x_hours:
          one: ~ 1h
          other: ~ %{count}h
        about_x_months:
          one: ~ 1mo
          other: ~ %{count}mo
        about_x_years:
          one: ~ 1y
          other: ~ %{count}y
        almost_x_years:
...

文档中也提供了此信息: https ://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words

于 2021-06-17T16:44:10.733 回答
2

这里有一些其他的方法来做到这一点。您像平常一样运行该方法,然后在字符串上使用gsub 。

链式

string.gsub(/ mi.*/, 'm')
      .gsub(/ h.*/, 'h')
      .gsub(/ d.*/, 'd')
      .gsub(/ mo.*/, 'mo')
      .gsub(/ y.*/, 'y')

哈希

string.gsub(/ .+/, { 
  ' minute'=> 'm', ' minutes'=>'m', 
  ' hour' => 'h', ' hours' => 'h', 
  ' day' => 'd', ' days' => 'd', 
  ' month' => 'mo', ' months' => 'mo', 
  ' year' => 'y', ' years' => 'y' 
})

堵塞

string.gsub(/ .+/) { |x| x[/mo/] ? 'mo' : x[1] }

除了字符串是"less than a minute". 链式解决方案返回"less than a minute"。哈希解决方案返回"less". 块解决方案返回"lesst"

只需为这种情况更改语言环境文件

en:
  datetime:
    distance_in_words:
      less_than_x_minutes:
        one: '<1m'

或者在方法的顶部添加一个 return to 子句

def my_method(string)
  return '<1m' if string == 'less than a minute'
  # code
end

注意:不包括选项的解决include_seconds: true方案。

于 2018-04-30T04:38:37.803 回答