Reputation: 97
i have an concept getting all the sundays in the particular month
I have an array , which has month and the year as
array=(Septmeber 2013, October 2013,January 2013,July 2013,May 2013)
now by keeping this array i want to get all the sundays(Date of Sundays) available in the array month, my array is dynamic , so according to the month ,i need all the sundays available
EG: if array is Septmeber 2013
mynewarray= (septmeber 1 2013,september 8 2013, september 15 2013, september 15 2013,september 22 2013, september 29 2013)
i want in a new array like this format
Pls Help
Thanks in Advance ....
Upvotes: 3
Views: 675
Reputation: 9002
OK here goes, assuming you also want your output as an array of strings in the format "September 1 2013"...
// Input array
NSArray *array = @[@"September 2013", @"February 2013", @"October 2013", @"January 2013", @"July 2013", @"May 2013"];
// Output array
NSMutableArray *output = [NSMutableArray array];
// Setup a date formatter to parse the input strings
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
inputFormatter.dateFormat = @"MMMM yyyy";
// Setup a date formatter to format the output strings
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
outputFormatter.dateFormat = @"MMMM d yyyy";
// Gregorian calendar for use in the loop
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Iterate each entry in the array
for (NSString *monthYear in array)
{
@autoreleasepool
{
// Parse the entry to get the date at the start of each month and it's components
NSDate *startOfMonth = [inputFormatter dateFromString:monthYear];
NSDateComponents *dateComponents = [calendar components:NSMonthCalendarUnit | NSYearCalendarUnit fromDate:startOfMonth];
// Iterate the days in this month
NSRange dayRange = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:startOfMonth];
for (ushort day = dayRange.location; day <= dayRange.length; ++day)
{
@autoreleasepool
{
// Assign the current day to the components
dateComponents.day = day;
// Create a date for the current day
NSDate *date = [calendar dateFromComponents:dateComponents];
// Sunday is day 1 in the Gregorian calendar (https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDateComponents/weekday)
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:date];
if (components.weekday == 1)
{
[output addObject:[outputFormatter stringFromDate:date]];
}
}
}
}
}
NSLog(@"%@", output);
// Release inputFormatter, outputFormatter, and calendar if not using ARC
There may be better ways of doing this, I'm not massively happy with it but it does the job.
Upvotes: 4