这是交易:我需要填写一个工作日日期(Mo-fr)的数组,从现在开始直到下周末。例如:
今天的日期:12月13日星期三
输出:
workdayArray{
[0] => 2013/12/13 00:00:00 (Wed)
[1] => 2013/12/14 00:00:00 (Thur)
[2] => 2013/12/15 00:00:00 (Fri)
[3] => 2013/12/18 00:00:00 (Mo)
[4] => 2013/12/19 00:00:00 (Tue)
[5] => 2013/12/20 00:00:00 (Wed)
[6] => 2013/12/21 00:00:00 (Thur)
[7] => 2013/12/22 00:00:00 (Fri)
}
以下是我的尝试:
//Our array we want to populate
NSMutableArray *ScheduleDays = [[NSMutableArray alloc] init];
//Setting timezone
NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
//Setting today's date and weekday
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.firstWeekday = 2;
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
int weekday = [comps weekday];
//hardcoding iterations needed to fetch all dates
int counter=7;
switch(weekday){
case 1: counter=13; break;
case 2: counter=12; break;
case 3: counter=11; break;
case 4: counter=10; break;
case 5: counter=9; break;
case 6: counter=8; break;
case 7: counter=14; break;
}
//Populating ScheduleDays while skipping Saturday and Sunday
NSDate *date = today;
for(int x=0;x<counter;x++){
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *formatWeekday = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [formatWeekday weekday];
if (weekday!=1 & weekday!= 7) {
[ScheduleDays addObject:date];
}
date = [date dateByAddingTimeInterval:60*60*24*1];
}
“它有效,有什么问题?” 当需要硬编码迭代和跳过工作日时,它似乎是一个非常草率的代码(我认为)。我试图找出如何设计一种有效的方法,而不是基于工作日的硬编码迭代等。对这个设计问题的任何帮助或想法都会很棒。