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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With