仅获得两个日期之间的周末
Posted
技术标签:
【中文标题】仅获得两个日期之间的周末【英文标题】:Get only weekends between two dates 【发布时间】:2012-01-26 19:16:42 【问题描述】:我试图只获得两个日期之间的周六和周日,但我不知道为什么要让我每周有空闲的日子。
这是我的代码:
- (BOOL)checkForWeekend:(NSDate *)aDate
BOOL isWeekendDate = NO;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
NSUInteger weekdayOfDate = [components weekday];
if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length)
// The date falls somewhere on the first or last days of the week.
isWeekendDate = YES;
return isWeekendDate;
- (void)viewWillAppear:(BOOL)animated
[super viewWillAppear:animated];
NSString *strDateIni = [NSString stringWithString:@"28-01-2012"];
NSString *strDateEnd = [NSString stringWithString:@"31-01-2012"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [df dateFromString:strDateIni];
NSDate *endDate = [df dateFromString:strDateEnd];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
// int months = [comps month];
int days = [comps day];
for (int i=0; i<days; i++)
NSTimeInterval interval = i;
NSDate * futureDate = [startDate dateByAddingTimeInterval:interval];
BOOL isWeekend = [self checkForWeekend:futureDate]; // Any date can be passed here.
if (isWeekend)
NSLog(@"Weekend date! Yay!");
else
NSLog(@"Not is Weekend");
问题:
这个问题是由NSTimeInterval interval = i;
引起的,for循环的逻辑是按天迭代。将时间间隔设置为 i 以秒为单位进行迭代。
来自 NSTimeInterval 的文档
NSTimeInterval 总是以秒为单位指定;
答案:
将NSTimeInterval
行改为
NSTimeInterval interval = i*24*60*60;
【问题讨论】:
NSTimeInterval 间隔 = i*24*60*60;解决了!!! 我将您的答案编辑为您的问题。您可以编辑自己的问题和答案。我在编辑中进一步澄清了推理。 【参考方案1】:Here is a link to another answer 我在 SO 上发帖(无耻,我知道)。它有一些代码可以帮助您了解未来的日期。这些方法被实现为 NSDate 的类别,这意味着它们成为 NSDate 的方法。
那里有几个功能可以帮助您度过周末。但这两个可能最有帮助:
- (NSDate*) theFollowingWeekend;
- (NSDate *) thePreviousWeekend;
他们返回接收者(自己)之后和之前的周末日期。
一般来说,你不应该使用一天是 86400 秒的概念,而应该使用 NSDateComponents 和 NSCalendar。即使在日期之间发生夏令时转换,这也有效。像这样:
- (NSDate *) dateByAddingDays:(NSInteger) numberOfDays
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = numberOfDays;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
【讨论】:
【参考方案2】:要记住的一件非常重要的事情是,一天并不(必然)等于 24*60*60 秒。而且你不应该自己做日期算术
您真正需要做的事情可能看起来有点乏味,但这是正确的做法:使用NSCalendar
和– dateByAddingComponents:toDate:options:
请参阅Calendrical Calculations 指南。
【讨论】:
我的意思是感谢您提到这一点。它被许多人忽视了。以上是关于仅获得两个日期之间的周末的主要内容,如果未能解决你的问题,请参考以下文章