Objective-C: Subtract after 100 years

How to subtract 100 years from NSDate?

I have it:

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.

+8
objective-c nsdate
source share
2 answers

Use NSCalendar and NSDateComponents to calculate the date.

 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 perform date calculations yourself: The problem with time and time zones is computer printing

+24
source share

You should really use NSCalendar and NSDateComponents for such calculations, as they can become very complex and can be full of annoying cases.

If you use NSCalendar and NSDateComponents (like the code below), it will take care of all things, such as 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 wrote about working with dates in Objective-C in general, if you need further reading on this.

+16
source share

All Articles