【问题标题】:Compare two NSDates比较两个 NSDate
【发布时间】:2010-06-20 18:57:38
【问题描述】:

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

例如:

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

应该返回类似:2324(分钟),四舍五入秒,因为我真的不需要秒。

【问题讨论】:

    标签: cocoa compare nsdate


    【解决方案1】:

    尝试类似:

    int intervall = (int) [date1 timeIntervalSinceDate: date2] / 60;
    

    【讨论】:

    • 请注意,这可能会计算为负的分钟数,具体取决于哪个日期较早。如果该数字为负数,则取反,或使用absfabs 函数。
    【解决方案2】:

    这里是比较两个 NSDate 的完整 sn-p,根据您的查询,您可能会发现它更有用。

    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

    【讨论】:

      猜你喜欢
      • 2011-07-09
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多