我有一个概念获取特定月份的所有星期日
我有一个数组,其中包含月份和年份
array=(Septmeber 2013, October 2013,January 2013,July 2013,May 2013)
现在通过保留这个数组我想获得数组月份中所有可用的星期日(星期日日期),我的数组是动态的,所以根据月份,我需要所有可用的星期日
例如: 如果数组是 2013 年 9 月
mynewarray=(2013 年 9 月 1 日,2013 年 9 月 8 日,2013 年 9 月 15 日,2013 年 9 月 15 日,2013 年 9 月 22 日,2013 年 9 月 29 日)
我想要一个像这种格式的新数组
请帮忙
提前致谢....
最佳答案
好的,假设您还希望将输出作为格式为“2013 年 9 月 1 日”的字符串数组...
// 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
可能有更好的方法来做到这一点,我对它不是很满意,但它可以完成工作。
关于iphone - 如何获取一个月内的所有星期日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18799657/