3

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 ....

4

1 回答 1

4

好的,假设您还希望输出为格式为“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

可能有更好的方法可以做到这一点,我对此并不满意,但它确实有效。

于 2013-09-14T09:12:08.147 回答