How do you say在Ruby发表了“x分钟前”或“x小时前”或“x天前”的事情?

时间:2009-10-15 07:18:40

标签: ruby time formatting

如果我在Ruby中有时间变量,我怎么能说它引用了发生以下事件之一的事件:

“x分钟前”或“x小时前”或“x天前”

显然,如果2天前发生了什么事情,我不想在几分钟前发生这种情况。

4 个答案:

答案 0 :(得分:12)

这是与语言无关的版本,您应该可以将其转换为任何语言:

ONE_MINUTE = 60
ONE_HOUR = 60 * ONE_MINUTE
ONE_DAY = 24 * ONE_HOUR
ONE_WEEK = 7 * ONE_DAY
ONE_MONTH = ONE_DAY * 3652425 / 120000
ONE_YEAR = ONE_DAY * 3652425 / 10000

def when(then):
    seconds_ago = now() - then

    if seconds_ago < 0:
        return "at some point in the future (???)"
    if seconds_ago == 0:
        return "now"

    if seconds_ago == 1:
        return "1 second ago"
    if seconds_ago < ONE_MINUTE:
        return str(seconds_ago) + " seconds ago"

    if seconds_ago < 2 * ONE_MINUTE:
        return "1 minute ago"
    if seconds_ago < ONE_HOUR:
        return str(seconds_ago/ONE_MINUTE) + " minutes ago"

    if seconds_ago < 2 * ONE_HOUR:
        return "1 hour ago"
    if seconds_ago < ONE_DAY:
        return str(seconds_ago/ONE_HOUR) + " hours ago"

    if seconds_ago < 2 * ONE_DAY:
        return "1 day ago"
    if seconds_ago < ONE_WEEK:
        return str(seconds_ago/ONE_DAY) + " days ago"

    if seconds_ago < 2 * ONE_WEEK:
        return "1 week ago"
    if seconds_ago < ONE_MONTH:
        return str(seconds_ago/ONE_WEEK) + " weeks ago"

    if seconds_ago < 2 * ONE_MONTH:
        return "1 month ago"
    if seconds_ago < ONE_YEAR:
        return str(seconds_ago/ONE_MONTH) + " months ago"

    if seconds_ago < 2 * ONE_YEAR:
        return "1 year ago"
    return str(seconds_ago/ONE_YEAR) + " years ago"

请注意,年/月数据是近似值(基于平均值),但这并不重要,因为相对误差仍然非常低。

答案 1 :(得分:11)

如果你在轨道上:

time_ago_in_words

答案 2 :(得分:0)

你需要做这样的事情:

tnow = Time.now
elapsed = tnow - tevent # elapsed time in seconds

if (elapsed < 60)
  puts "#{elapsed} seconds ago"
elsif (elapsed < 60*60)
  puts "#{elapsed/60} minutes ago"
end

答案 3 :(得分:0)

如果您选择超出完整的Rails但愿意使用active_support(gem install actionview

,这是一个完整的示例
#!/usr/bin/env ruby

require 'active_support'
require 'active_support/core_ext/object/acts_like'
require 'active_support/core_ext/time/acts_like'
require 'action_view'

require 'date'

# Avoid a deprecation warning
I18n.enforce_available_locales = false

# Add time_ago_in_words
extend ActionView::Helpers::DateHelper

[
  '2014-04-24 16:20:00',
  '2014-04-21 16:20:00',
  '2014-03-24 16:20:00',
  '2013-04-20 16:20:00',
].map {|t| DateTime.parse t}.each do |time|
  puts time_ago_in_words time
end

在撰写本文时,输出:

about 6 hours
3 days
about 1 month
about 1 year