【问题标题】:calculating age method with Ruby用 Ruby 计算年龄方法
【发布时间】:2020-06-21 19:03:42
【问题描述】:

我需要创建一个计算年龄的方法,我可以按年计算,但如何准确地按日、月和年计算呢?

如果我今天做 - 生日我得到 12535/1

require 'date'

def age_in_days(day, month, year)
   birthdate = Date.new(year, month, day)
   today  = Date.today

   age = today.year - birthdate.year

   return birthdate, today, age
end

puts age_in_days(12, 10, 1990)

【问题讨论】:

  • 为了计算天数的差异,你看过修改后的儒略日数吗?例如today.mjd - birthdate.mjd查看这个答案:stackoverflow.com/a/4502336/1611339
  • 我不明白你的问题。我出生于 1915 年 2 月 12 日。如果今天的日期是 2020 年 3 月 13 日,答案会是 105 年、1 个月零 1 天,还是别的什么?如果是后者,你需要准确地描述你想要什么。
  • 注意:在 Ruby 中,您不需要显式的 return,而是可以使用 [ birthdate, today, age ]

标签: ruby


【解决方案1】:

要计算考虑日月和年的差异,您可以使用以下方法。

require 'date'

def age_in_years(day, month, year)   
  birthdate = Time.new(year, month, day)
  avg_seconds_in_year = 31557600
  seconds = (Time.now- birthdate).to_i
  years = seconds/avg_seconds_in_year
  years
end

puts age_in_years(12, 10, 1990)

将输出29

这个答案取决于一年平均有 365.25 天,即 31557600 秒这一事实。

现在在方法中您可以看到seconds 表示以秒为单位的差异。现在从那里你可以计算年份(就像我除以 31557600 所做的那样)。您还可以计算月、日、小时、分钟、秒的差异。

如果你想让函数以天、小时、分钟和秒为单位返回年龄,那么以下将做到这一点:

require 'date'

def age_in_days(day, month, year) 
  birthdate = Time.new(year, month, day)
  seconds = (Time.now- birthdate).to_i
  mm, ss = seconds.divmod(60)
  hh, mm = mm.divmod(60)
  dd, hh = hh.divmod(24)
  "#{dd} days, #{hh} hours, #{mm} minutes and #{ss} seconds"
end

puts age_in_days(12, 10, 1990)

将输出10845 days, 14 hours, 41 minutes and 55 seconds

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2020-12-28
    • 2016-03-20
    • 2011-04-16
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多