Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Subtract 100 years from now [duplicate]

How do I subtract 100 years from NSDate now?

I have this:

NSDate *now = [NSDate date];
NSDate *hundredYearsAgo = [now dateByAddingTimeInterval:100*365*24*60*60];

But this does not take into account that there are years with 365 days and years with 366 days.

like image 819
mrd Avatar asked Jan 24 '14 14:01

mrd


Video Answer


2 Answers

Use NSCalendar and NSDateComponents for date calculations.

unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
NSDate *now = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:now];
[comps setYear:[comps year] - 100];
NSDate *hundredYearsAgo = [gregorian dateFromComponents:comps];

Then watch this video, explaining why you should never do date calculations yourself:
The Problem with Time & Timezones - Computerphile

like image 158
DrummerB Avatar answered Sep 21 '22 20:09

DrummerB


You should really use NSCalendar and NSDateComponents for calculations like that since they can get very tricky and can be full of annoying edge cases.

If you use NSCalendar and NSDateComponents (like the code below) it will take care of all the things like leap years for you.

NSDate *now = [NSDate date];
NSDateComponents *minusHundredYears = [NSDateComponents new];
minusHundredYears.year = -100;
NSDate *hundredYearsAgo = [[NSCalendar currentCalendar] dateByAddingComponents:minusHundredYears
                                                                        toDate:now
                                                                       options:0];

I've written about working with dates in Objective-C general if you want some extra reading on the subject.

like image 25
David Rönnqvist Avatar answered Sep 20 '22 20:09

David Rönnqvist