How many days are left this year in Objective C

Screen Shot 2014-01-07 at 12.55.39Like many date related operations, this isn’t as straightforward for a computer as it is for a human brain. Besides, it needs to be time-travel save as well as future proof. Here’s how we do it:

First we create a Gregorian calendar object and extract the current year from it. Next we’ll add the date components to it that make up New Year’s Eve, which will give us a second date object.

Now that we have two dates, we compare them via the NSCalendar method fromDate:toDate. This in turn will result in a new date component from which we can extract the days.

// what year is this? who's the president?
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:today];
NSInteger currentYear = [components year];

NSLog(@"The year is %i", currentYear);

// create a date with the end of the year
[components setDay:31];
[components setMonth:12];
NSDate *newYearsEve = [gregorian dateFromComponents:components];

// determine how many days are left until the end of the year
NSDateComponents *daysLeftComponents = [gregorian components:NSDayCalendarUnit fromDate:today toDate:newYearsEve options:0];
NSInteger daysLeft = [daysLeftComponents day];

NSLog(@"Days to New Years Eve: %ld", (long)daysLeft);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.