gpt4 book ai didi

objective-c - 仅获取两个日期之间的周末

转载 作者:行者123 更新时间:2023-12-03 17:35:52 24 4
gpt4 key购买 nike

我试图只获取两个日期之间的周六和周日,但我不知道为什么要在一周内获取空闲日。

这是我的代码:

- (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 is always specified in seconds;

答案:

NSTimeInterval 行更改为

NSTimeInterval interval = i*24*60*60;

最佳答案

Here is a link to another answer我在SO上发帖(我知道无耻)。它有一些代码可以帮助您确定 future 的日期。这些方法作为 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];
}

关于objective-c - 仅获取两个日期之间的周末,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9023891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com