Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Last active August 29, 2015 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamatama41/3c8cf6dda0a6d57139d8 to your computer and use it in GitHub Desktop.
Save kamatama41/3c8cf6dda0a6d57139d8 to your computer and use it in GitHub Desktop.
永遠の17歳。 Java8でコンパイル・実行してね。
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class 日本人 {
protected final String name;
protected final OffsetDateTime birthdate;
public 日本人(String name, String birthdate) {
this.name = name;
// 2011-12-03T00:00:00+09:00
this.birthdate = OffsetDateTime.parse(birthdate+"T00:00:00+09:00", DateTimeFormatter.ISO_DATE_TIME);
}
public int getAge() {
return getAge(OffsetDateTime.now());
}
protected int getAge(OffsetDateTime today) {
int age = today.getYear() - birthdate.getYear();
if(today.getDayOfYear() < birthdate.getDayOfYear()) {
age -= 1;
}
return age;
}
@Override
public String toString() {
return String.format("%s(%d)", name, getAge());
}
public static void main(String[] args) {
// 山田太郎(35) *2015/02/20時点
System.out.println(new 日本人("山田太郎", "1980-01-01"));
// 田村ゆかり(17歳と263ヶ月) *2015/02/20時点
System.out.println(new 永遠の17歳("田村ゆかり", "1976-02-27"));
// 堀江由衣(17歳と257ヶ月) *2015/02/20時点
System.out.println(new 永遠の17歳("堀江由衣", "1976-09-20"));
// 井上喜久子(17歳と400ヶ月) *2015/02/20時点
System.out.println(new 永遠の17歳("井上喜久子", "1964-09-25"));
}
}
class 永遠の17歳 extends 日本人 {
private static final int SEVENTEEN = 17;
public 永遠の17歳(String name, String birthdate) {
super(name, birthdate);
}
private int howManyMonthsHasPassedFrom17(OffsetDateTime today) {
int pastYears = today.getYear() - birthdate.getYear() - SEVENTEEN;
int surplus = today.getMonthValue() - birthdate.getMonthValue();
if(today.getDayOfMonth() < birthdate.getDayOfMonth()) {
surplus -= 1;
}
return (pastYears * 12) + surplus;
}
@Override
protected int getAge(OffsetDateTime today) {
return SEVENTEEN;
}
@Override
public String toString() {
OffsetDateTime today = OffsetDateTime.now();
return String.format("%s(%d歳と%dヶ月)", name, SEVENTEEN, howManyMonthsHasPassedFrom17(today));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment