Reputation: 27
I am using this code
int unitFlags = NSMonthCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int months = [comps month];
I want actually the name of the month which is missing any idea?
Upvotes: 1
Views: 283
Reputation: 46543
I have solved this question in two ways, I don't know which one is better : (I am expecting people to comment on my answers)
As you want all the months name between start and end date, you can do as:
Method 1:
NSString *startString=@"23 Jun 2012";
NSString *endString=@"23 Dec 2013";
NSDateFormatter *dateFormatterDDMMMYYYY=[NSDateFormatter new];
[dateFormatterDDMMMYYYY setDateFormat:@"dd MMM yyyy"];
NSDate *startDate=[dateFormatterDDMMMYYYY dateFromString:startString];
NSDate *endDate=[dateFormatterDDMMMYYYY dateFromString:endString];
NSMutableArray *betweenMonths=[NSMutableArray new];
NSDate *tempDate=startDate;
while (tempDate<endDate) {
NSDateFormatter *dateFormatterMMM=[NSDateFormatter new];
[dateFormatterMMM setDateFormat:@"MMM"];
NSString *monthName=[dateFormatterMMM stringFromDate:tempDate];
[betweenMonths addObject:monthName];
//tempDate is calculted after storing because you not need the last month.
NSCalendar *calendar=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components=[NSDateComponents new];
components.month=1;
tempDate=[calendar dateByAddingComponents:components toDate:tempDate options:0];
}
NSLog(@"Month Name : %@",betweenMonths);
Method 2:
NSString *startString=@"23 Jun 2012";
NSString *endString=@"23 Dec 2013";
NSDateFormatter *dateFormatterDDMMMYYYY=[NSDateFormatter new];
[dateFormatterDDMMMYYYY setDateFormat:@"dd MMM yyyy"];
NSDate *startDate=[dateFormatterDDMMMYYYY dateFromString:startString];
NSDate *endDate=[dateFormatterDDMMMYYYY dateFromString:endString];
NSInteger month = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit
fromDate: startDate
toDate: endDate
options: 0] month];
NSDateFormatter *dateFormatterMMM=[NSDateFormatter new];
[dateFormatterMMM setDateFormat:@"MMM"];
NSString *startMonth=[dateFormatterMMM stringFromDate:startDate];
NSArray *months=@[@"Jan",@"Feb",@"Mar",@"Apr",@"May",@"Jun",@"Jul",@"Aug",@"Sep",@"Oct",@"Nov",@"Dec"];
NSInteger startDateMonth=[months indexOfObject:startMonth];
for (NSInteger i=startDateMonth+1; i<startDateMonth+month; i++) {
NSLog(@"Moths : %@",months[i%12]); //%12 for checking if i goes beyond 11, as endDate may be more then one year span long
}
Upvotes: 2