定食屋おろポン

おろしポン酢と青ネギはかけ放題です

そういえば誕生日

もう数日前だけど。何歳になったのか計算してみました。

Cocoa

- (id)init
{
    self = [super init];
    if (self) {
        NSLog(@"%d", self.age); // => 25
    }
}
- (int)age
{
    NSCalendar*         cal;
    NSDate*             currentDate;
    NSDateComponents*   birthdayComponents;
    NSDateComponents*   components;
    cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    currentDate = [NSDate date];
    birthdayComponents = [[NSDateComponents alloc] init];
    [birthdayComponents setYear:1987];
    [birthdayComponents setMonth:2];
    [birthdayComponents setDay:13];
    components = [cal components:NSYearCalendarUnit 
                        fromDate:[cal dateFromComponents:birthdayComponents] 
                          toDate:currentDate
                         options:0];
    
    return [components year];
}

日付計算は端数があると想定外の動きをしてしまいがちだよね。
例えば1/1 12:00と2/1 11:00の間隔は、30日と23時間となるため。純粋に日付の間隔を取る場合にはfromDate, toDateともに時刻を0:00に合わせると幸せになる。具体的には

currentDate = [cal dateFromComponents:[cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                                fromDate:[NSDate date]]];

みたいに時刻をそぎ落とす。でも今回は必要ないのでそのまま。

Ruby

currentTime = Time.new
birthday = Time.mktime(1987, 2, 13)
case
when currentTime.month < birthday.month then
	age = currentTime.year - birthday.year - 1
when currentTime.month == birthday.month then
	age = if currentTime.day < birthday.day then currentTime.year - birthday.year - 1
			else currentTime.year - birthday.year
			end
else age = currentTime.year - birthday.year
end

p age # => 25

elseじゃなくてcurrentTime.month < birthday.month then
にしたほうが統一感あっていいのかな。

抱負

プログラミング初心者って↑みたいにどうでもいいことをコードで書いて悦に入るのが好きだよね。
25歳の抱負は「脱初心者」です。