【问题标题】:Comparing NSDates to check if today falls in between比较 NSDates 以检查今天是否介于两者之间
【发布时间】:2011-05-09 02:57:07
【问题描述】:

感谢你们,我已成功地将我的字符串数组转换为 NSDates。现在我正在尝试检查今天的日期是否在我的两个日期之间(即 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
    }

【问题讨论】:

  • 不确定我知道问题是什么?
  • 检查 'todaysDate' 是否介于 'fromDate' 和 'toDate' 之间

标签: objective-c nsdate


【解决方案1】:

执行以下操作,

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

NSTimeInterval 基本上是一种双精度类型,因此您可以比较 currTime 是否大于一个且小于另一个,而不是日期介于这两个 NSDate 之间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2011-08-12
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多