33
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

生年月日から年齢を計算

Last updated at Posted at 2013-10-19

元ネタ:みんなのちからになりたい

####公式:(今日の日付-誕生日)/10000の小数点以下切捨て。

[1] pry(main)> require "date"
=> true
[2] pry(main)> d1 = Date.new(1980, 1, 1).strftime("%Y%m%d").to_i
=> 19800101
[3] pry(main)> d2 = Date.today.strftime("%Y%m%d").to_i
=> 20130219
[4] pry(main)> (d2 - d1) / 10000
=> 33

例えば生年月日がDBに格納されているPersonクラスで

class Person < ActiveRecord::Base
  attr_accessible :birthdate
  def age
    d1=self.birthdate.strftime("%Y%m%d").to_i
    d2=Date.today.strftime("%Y%m%d").to_i
    return (d2 - d1) / 10000
  end
end

#使い方
person=Person.find(:first)
person.age

33
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?