10/03/2011 11:23:00
日付、誕生日から年齢を求めるプログラム(Java)
自分メモ用にtumblrに投稿。
後輩が日付から誕生日を求めるロジックを作ってくださいと頼まれていたのを聞き、
きっと、次の仕事でも同じようなロジック作ることになるだろうなということで、
なんとなく作ってみた。
以下のURLを参考に作ってみた。
→参考URL:http://delfusa.main.jp/delfusafloor/technic/technic/060_GetAge.html
package test;
import java.util.GregorianCalendar;
public class TestBirthDay {
/**
* @param args
*/
public static void main(String[] args) {
int age = 0;
String birthDate = "19770311";
String chkDate = "20110229";
age = getAge(birthDate, chkDate);
System.out.println ("chkDate = " + chkDate+ " birthDate = " + birthDate + "age = " + age);
}
/**
* 指定した日付のより年齢を求めるメソッド です。
*
* @param birthDate 誕生日(yyyymmdd)
* @param chkDate チェックしたい日付(yyyymmdd)
* @return 年齢
*/
private static int getAge(String birthDate, String chkDate) {
int result = 0;
String birthYear = birthDate.substring(0, 4);
String birthMonth = birthDate.substring(4, 6);
String birthDay = birthDate.substring(6, 8);
String chkYear = chkDate.substring(0, 4);
String chkMonth = chkDate.substring(4, 6);
String chkDay = chkDate.substring(6, 8);
int b_year = Integer.parseInt(birthYear);
int b_month = Integer.parseInt(birthMonth);
int b_day = Integer.parseInt(birthDay);
int c_year = Integer.parseInt(chkYear);
int c_month = Integer.parseInt(chkMonth);
int c_day = Integer.parseInt(chkDay);
GregorianCalendar gCal = new GregorianCalendar();
//現在(任意の年月日)の「年」から誕生日の「年」を引く
result = c_year - b_year;
//チェックしたい年がうるう年ではない場合
if (!gCal.isLeapYear(c_year)) {
//誕生日がうるう日なら
if (b_month == 2 && b_day == 29) {
b_month = 3;
b_day = 1;
} //誕生日を3/1にしておく
}
//その年の誕生日を過ぎていなければさらに1歳引く
if (c_month < b_month) {
result -= 1;
} else if (c_month == b_month) {
if (c_day < b_day) {
result -= 1;
}
}
return result;
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------