我的应用程序显示根据当前日期更改UILabel的值:
当前实施:
NSDate* todaysdate = [NSDate date];
NSDateComponents *week1startcomp = [[NSDateComponents alloc] init];
[week1startcomp setMonth:8];
[week1startcomp setDay:4];
[week1startcomp setYear:2014];
NSDate* week1start = [[NSCalendar currentCalendar] dateFromComponents:week1startcomp];
NSDateComponents *week1endcomp = [[NSDateComponents alloc] init];
[week1endcomp setMonth:9];
[week1endcomp setDay:4];
[week1endcomp setYear:2014];
NSDate* week1end = [[NSCalendar currentCalendar] dateFromComponents:week1endcomp];
NSDateComponents *week2startcomp = [[NSDateComponents alloc] init];
[week2startcomp setMonth:9];
[week2startcomp setDay:9];
[week2startcomp setYear:2014];
NSDate* week2start = [[NSCalendar currentCalendar] dateFromComponents:week2startcomp];
NSDateComponents *week2endcomp = [[NSDateComponents alloc] init];
[week2endcomp setMonth:9];
[week2endcomp setDay:15];
[week2endcomp setYear:2014];
NSDate* week2end = [[NSCalendar currentCalendar] dateFromComponents:week2endcomp];
NSDateComponents *week3startcomp = [[NSDateComponents alloc] init];
[week3startcomp setMonth:9];
[week3startcomp setDay:16];
[week3startcomp setYear:2014];
NSDate* week3start = [[NSCalendar currentCalendar] dateFromComponents:week3startcomp];
NSDateComponents *week3endcomp = [[NSDateComponents alloc] init];
[week3endcomp setMonth:9];
[week3endcomp setDay:29];
[week3endcomp setYear:2014];
NSDate* week3end = [[NSCalendar currentCalendar] dateFromComponents:week3endcomp];
等等17周:
if([todaysdate compare:week1start] == NSOrderedDescending && [todaysdate compare:week1end] == NSOrderedAscending){
NSLog(@"Current week is Week 1");
_currentWeekLabel.text = @"Currently in Week 1";
}else if([todaysdate compare:week2start] == NSOrderedDescending && [todaysdate compare:week2end] == NSOrderedAscending){
NSLog(@"Current week is Week 2");
_currentWeekLabel.text = @"Currently in Week 2";
}else if([todaysdate compare:week3start] == NSOrderedDescending && [todaysdate compare:week3end] == NSOrderedAscending){
NSLog(@"Current week is Week 3");
_currentWeekLabel.text = @"Currently in Week 3";
}
有没有更好的方法来实现这一目标?它目前工作正常(除了日期落在范围的第一天或最后一天时的逻辑问题)。
欢迎提出任何建议。
答案 0 :(得分:0)
程序几乎相同,它可以帮助您减少代码。写一个像这样的方法:
- (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
然后这样做:
if([self date:todaysdate isBetweenDate:week1start andDate:week1end]){
NSLog(@"Current week is Week 1");
_currentWeekLabel.text = @"Currently in Week 1";
}else if([self date:todaysdate isBetweenDate:week2start andDate:week2end]){
NSLog(@"Current week is Week 2");
_currentWeekLabel.text = @"Currently in Week 2";
}else if([self date:todaysdate isBetweenDate:week3start andDate:week3end]){
NSLog(@"Current week is Week 3");
_currentWeekLabel.text = @"Currently in Week 3";
}
希望这会有所帮助.. :)