gpt4 book ai didi

objective-c - 比较 NSDates 以检查今天是否介于两者之间

转载 作者:搜寻专家 更新时间:2023-10-30 20:04:07 26 4
gpt4 key购买 nike

感谢你们,我已经成功地将我的字符串数组转换为 NSDates。现在我正在尝试检查今天的日期是否在我的 2 个日期(即 fromDate 和 toDate)之间。我已经看到以下问题,但未能在我的代码中实现它们。太棒了我可以有任何其他方法或帮助使用用户提供的解决方案。

NSDate between two given NSDates

How to Check if an NSDate occurs between two other NSDates

How can I check if an NSDate falls in between two other NSDates in an NSMutableArray

这是我目前拥有的:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd"];
NSTimeZone *tz = [NSTimeZone localTimeZone];
[format setTimeZone:tz];
NSDate *now = [[NSDate alloc] init];
NSString *todaysDate = [format stringFromDate:now];
NSLog(@"todaysDate: %@", todaysDate);

//converting string - date
int size = [appDelegate.ALLevents count];
for (NSUInteger i = 0; i < size; i++) {
Event *aEvent = [appDelegate.ALLevents objectAtIndex:i];

//Convert fromDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *fromDate = [dateFormatter dateFromString:aEvent.fromDate];
[dateFormatter setTimeZone:tz];
NSLog(@"fromDate: %@", fromDate);

//Convert toDate
NSDate *toDate = [dateFormatter dateFromString:aEvent.toDate];
NSLog(@"toDate: %@", toDate);
[dateFormatter release];
//Compare if today falls in between
//codes here
}

最佳答案

执行以下操作,

NSTimeInterval fromTime = [fromDate timeIntervalSinceReferenceDate];
NSTimeInterval toTime = [toDate timeIntervalSinceReferenceDate];
NSTimeInterval currTime = [[NSDate date] timeIntervalSinceReferenceDate];

NSTimeInterval 基本上是 double 类型,因此您可以比较 currTime 是否大于 1 且小于 other 是否日期落在这两个 NSDate 之间。

关于objective-c - 比较 NSDates 以检查今天是否介于两者之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5932044/

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