I'm getting a 0 for the month when I try to get the date difference from now and the end of the year. I'm using a NSCalendar
object to get the difference between two NSDate
objects.
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2013];
[comps setMonth:0];
[comps setDay:0];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate = [calendar dateFromComponents:comps];
NSDateComponents *timeDifference = [[NSCalendar currentCalendar]
components: NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |
NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:[NSDate date] toDate:newDate options:0];
int months = timeDifference.month;
int days = timeDifference.day;
if (months>0)
days+=31;
int hours = timeDifference.hour;
int minutes = timeDifference.minute;
int seconds = timeDifference.second;
You're trying to calculate number of months, days, etc to year 2013. In NSDateComponents
0 means 'no value', all values that count should be greater than 0. That's why your comps
value is considered as 'incomplete', which causes strange output from NSCalendar
.
Set month
and day
in lines 3-4 to 1 fix the issue.