Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
33
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

生年月日から年齢を計算

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

公式:(今日の日付-誕生日)/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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
33
Help us understand the problem. What are the problem?