2016-08-05 173 views
0
NSDate *currentTime = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
         [dateFormatter setDateFormat:@"hh:mm"]; 
NSString *resultString = [dateFormatter stringFromDate: currentTime]; 
NSDate* firstDate = [dateFormatter dateFromString:resultString]; 
NSDate* secondDate = [dateFormatter dateFromString:@"16:00"]; 
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate]; 

if (timeDifference < 0){ 

我试图检索当前时间并将其与输入时间进行比较。这是我的代码的一部分(iOS的目标c),但NSTimeInterval导致一个断点。除此之外,我还希望将该日期纳入比较,所以如果周二下午5点之后会发生事件。所以,如果你有任何想法如何纳入,以及将不胜感激!比较当前日期和时间iOS

+0

约翰的答案在下面是比较日期的基本形式。 (并且请注意,在比较之前不需要转换为字符串并返回。)关于“星期二下午5点以后”的内容有点鬼鬼祟祟,可能需要单独提问 - 需要指定不同时区的行为,不管它是“任何”星期二等 –

回答

2

若要比较两个日期:

if ([firstDate compare:secondDate] == NSOrderedDescending) { 
    NSLog(@"firstDate is later than secondDate"); 
    NSTimeInterval timeDifference = [firstDate timeIntervalSinceDate:secondDate]; 
} else if ([firstDate compare:secondDate] == NSOrderedAscending) { 
    NSLog(@"firstDate is earlier than secondDate"); 
    NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate]; 
} else { 
    NSLog(@"firstDate and secondDate are the same"); 
} 

这应该解决您的问题。

+0

如果我希望它只在某个特定的日子,该怎么办?假设在周二的5点会发生一个事件,但在5点周三它不会。 – DSmith

+2

@DSmith:像这样的NSDate对象体现的“日期”表示绝对全局意义上的现实世界时间中的特定单点。该时间点可以表示为特定时间段的日期和时间,或与其他特定时间点进行比较。它不会*表示一般的“时间”或任何其他一般概念。如果你想弄清楚如何表示你正在寻找的东西,你可能想要更具体地问这个问题,以获得最佳的建模帮助。 –

0
NSDate *currentTime = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
         [dateFormatter setDateFormat:@"hh:mm"]; 
NSString *resultString = [dateFormatter stringFromDate: currentTime]; 
NSDate* firstDate = [dateFormatter dateFromString:resultString]; 
NSDate* secondDate = [dateFormatter dateFromString:@"16:00"]; 
NSComparisonResult result = [secondDate compare:firstDate]; 
     switch(result){ 
      case NSOrderedDescending: 
       NSLog(@"date1 is later than date2"); 
       break; 
      case NSOrderedAscending: 
       NSLog(@"date1 is earlier than date2"); 
       break; 
      default: 
       NSLog(@"dates are the same"); 
       break; 
     }