Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Ruby计算年龄的方法_Ruby - Fatal编程技术网

用Ruby计算年龄的方法

用Ruby计算年龄的方法,ruby,Ruby,我需要创建一个计算年龄的方法,我可以按年计算,但如何准确地按日、按月和按年计算呢 如果我只是做今天-生日我得到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 e

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

如果我只是做今天-生日我得到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)


要计算日、月和年的差异,可以使用以下方法

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天、14小时、41分钟和55秒

要计算日、月和年的差异,可以使用以下方法

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天14小时41分55秒

为计算天数差异,您是否查看了修改后的朱利安日数?e、 g
today.mjd-birthdate.mjd
看看这个答案:我不明白你的问题。我出生于1915年2月12日。如果今天的日期是2020年3月13日,答案是105年1个月1天,还是别的什么?如果是后者,您需要精确地描述您想要的内容。注意:在Ruby中,您不需要显式的
返回值
,相反,您可以执行
[生日,今天,年龄]
。要计算天数差异,您是否查看了修改后的朱利安日数?e、 g
today.mjd-birthdate.mjd
看看这个答案:我不明白你的问题。我出生于1915年2月12日。如果今天的日期是2020年3月13日,答案是105年1个月1天,还是别的什么?如果是后者,您需要精确地描述您想要的内容。注意:在Ruby中,您不需要显式的
返回
,而是可以执行
[生日、今天、年龄]