I want to find number of day today is in current year. e.g, if today is Mar15, 2012 I should get 75(31 + 29 + 15). Or we can simply say that number of days between today and
Using the NSDate
, NSDateComponents
and NSCalendar
classes, you can quite easily calculate the amount of days between the last day of the previous year and today (which is the same as calculating today's number in the current year):
// create your NSDate and NSCalendar objects
NSDate *today = [NSDate date];
NSDate *referenceDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
// get today's date components
NSDateComponents *components = [calendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:today];
// changing the date components to the 31nd of December of last year
components.day = 31;
components.month = 12;
components.year--;
// store these components in your date object
referenceDate = [calendar dateFromComponents:components];
// get the number of days from that date until today
components = [calendar components:NSDayCalendarUnit fromDate:referenceDate toDate:[NSDate date] options:0];
NSInteger days = components.day;