Challenge Solution


#1

Hi guys,

Well, the book basically gave us the solution at the end of the chapter. Here is my code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSDateComponents *comps = [[NSDateComponents alloc]init];
        
        [comps setYear:1988];
        [comps setMonth:12];
        [comps setDay:24];
        [comps setHour:25];
        [comps setMinute:60];
        [comps setSecond:0];

        NSCalendar *g = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

        NSDate *dateOfBirth = [g dateFromComponents:comps];

        NSLog ( @ "Your D.O.B is: %@", dateOfBirth);

        NSDate *now = [NSDate date];

        double secondsAlive = [now timeIntervalSinceDate:dateOfBirth];

        NSLog (@ "You've been alive for %.0f seconds", secondsAlive);
        
        
        }
    return 0;
}

The output:

013-06-11 15:03:57.682 TimeAfterTime[14386:303] Your D.O.B is: 1988-12-25 00:00:00 +0000
2013-06-11 15:03:57.682 TimeAfterTime[14386:303] You've been alive for 771944638 seconds

Question:

Why do we specify hour as 25 (To get 12pm at night) when there isn’t 25 hours in a day?


#2

[quote=“Tander”]Question:

Why do we specify hour as 25 (To get 12pm at night) when there isn’t 25 hours in a day?[/quote]

Shouldn’t midnight be 0 (zero)?


#3

[quote=“Zachariah”][quote=“Tander”]Question:

Why do we specify hour as 25 (To get 12pm at night) when there isn’t 25 hours in a day?[/quote]

Shouldn’t midnight be 0 (zero)?[/quote]

Yes. He made it a little bit more complicated than it should be. Since this is all addition, the correct date ends up coming out, but setting hours to 25 and minutes to 60 is the same as incrementing the day by 1 and leaving those 2 as 0. Doing that in the solution is making it more complicated than it needs to be.