Reputation: 1807
I'm new to ios programming.
I'm trying to get the date of death by the code below. But, I get the unexpected result.
In the example code below, someone's birthdate is 1899-12-31 and this person's death age is 80.
So, I'm expecting this person's deathdate is 1979-12-31. But, the result I get is 1843-11-05 08:31:44 +0000.
Could anyone please tell me what's wrong with this code?
Thanks!!
NSInteger year = [_selectedDeathAge intValue];
NSLog(@"%d", year); //80
NSLog(@"%@", _selectedBirthDate);//(NSDate)1899-12-31 15:00:00 +0000
NSDate *deathDate = [_selectedBirthDate initWithTimeInterval:year * 365 * 24 * 60 * 60 sinceDate:_selectedBirthDate];
NSLog(@"%@", deathDate);//(NSDate)1843-11-05 08:31:44 +0000
Upvotes: 1
Views: 465
Reputation: 163268
Don't use NSDate
to do relative date computations. Use NSCalendar
and NSDateComponents
:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *yearsComponents = [[NSDateComponents alloc] init];
yearsComponents.year = [_selectedDeathAge intValue];
NSDate *deathDate = [cal dateByAddingComponents:yearsComponents toDate:_selectedBirthDate];
Upvotes: 2
Reputation: 318854
You should not be calling the initWithTimeInterval:sinceDate:
method on another instance.
You should be doing this instead:
NSDate *deathDate = [_selectedBirthDate dateByAddingTimeInterval:year * 365 * 24 * 60 * 60];
Or you can do it this way:
NSDate *deathDate = [[NSDate alloc] initWithWithTimeInterval:year * 365 * 24 * 60 * 60 sinceDate:_selectedBirthDate];
But in the end, you should use the solution from "Jacob Relkin". It's the better solution for this type of calculation.
Upvotes: 2
Reputation: 33421
NSDate *deathDate = [_selectedBirthDate initWithTimeInterval:year * 365 * 24 * 60 * 60 sinceDate:_selectedBirthDate];
This line is wrong, and you should expect strange results. You are calling init on an already initialized function. You need to create it via [[NSDate alloc] initWithTimeInterval:sinceDate:]
and furthermore, you should not hardcode the time interval like that. Look up NSDateComponents
.
Upvotes: 1