代码之家  ›  专栏  ›  技术社区  ›  Matt S.

比较两个nsdates

  •  7
  • Matt S.  · 技术社区  · 16 年前

    如何比较两个nsdates并返回它们之间的时间量。

    例如:

    2010-06-20 14:29:41 -0400
    2010-06-20 14:53:29 -0400
    

    应该返回如下内容: 23 24 (分钟),四舍五入秒,因为我不需要秒。

    2 回复  |  直到 14 年前
        1
  •  11
  •   phonecoddy    16 年前

    尝试以下方法:

    int intervall = (int) [date1 timeIntervalSinceDate: date2] / 60;
    
        2
  •  2
  •   Black Tiger    14 年前

    这里是比较两个nsdate的完整代码片段,您可以根据查询找到更有用的代码片段。

    NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSString *str =@"12:15, 01 15 2012 AM";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"hh:mm, dd MM yy a"];
    
    NSDate *refDate = [formatter dateFromString:str];
    NSDate *today = [NSDate date];
    
    
    
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *difference = [myCal components:unitFlags fromDate:refDate     toDate:today options:0];
    NSLog(@"%@",difference);
    

    ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    日历年:0月:0日:0小时:1分钟:19

    推荐文章