1

我的程序中有以下代码:

NSUInteger currentMinuteOrdinal = [[NSCalendar currentCalendar] ordinalityOfUnit:NSMinuteCalendarUnit inUnit:NSEraCalendarUnit forDate:[NSDate date]];
NSUInteger passedInMinuteOrdinal = [[NSCalendar currentCalendar] ordinalityOfUnit:NSMinuteCalendarUnit inUnit:NSEraCalendarUnit forDate:passedInDate];
NSUInteger minuteDifference = currentMinuteOrdinal - passedInMinuteOrdinal;

当前时间是今天下午 6:09。传入时间是今天下午 4 点 17 分。(我正在查看调试器中的值,所以我知道这些值是正确的。)然而这两个序数值总是得出相同的值,将“minuteDifference”呈现为 0。

这种方法根本行不通吗?还是我做错了什么?

谢谢。

4

1 回答 1

2

您的代码似乎对我有用(我复制/粘贴它),我看不到您如何处理passedInDate,我按照您指定的设置日期:

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];

//NSDate * dateA = [NSDate date];
NSDate * dateA = [formatter dateFromString:@"2009-12-15 06:09:00 +1100"];
NSDate * dateB = [formatter dateFromString:@"2009-12-15 04:17:00 +1100"];

NSUInteger currentMinuteOrdinal =
    [[NSCalendar currentCalendar] ordinalityOfUnit:NSMinuteCalendarUnit
                                            inUnit:NSEraCalendarUnit
                                           forDate:dateA];      // current

NSUInteger passedInMinuteOrdinal =
    [[NSCalendar currentCalendar] ordinalityOfUnit:NSMinuteCalendarUnit
                                            inUnit:NSEraCalendarUnit
                                           forDate:dateB];      // passed in

NSUInteger minuteDifference = currentMinuteOrdinal - passedInMinuteOrdinal;

NSLog(@" currentMinuteOrdinal: %d", currentMinuteOrdinal);
NSLog(@"passedInMinuteOrdinal: %d", passedInMinuteOrdinal);
NSLog(@"     minuteDifference: %d", minuteDifference);

在这种情况下输出:

2009-12-15 21:51:46.215 x[50036:903]  currentMinuteOrdinal: 1056606130
2009-12-15 21:51:46.216 x[50036:903] passedInMinuteOrdinal: 1056606018
2009-12-15 21:51:46.217 x[50036:903]      minuteDifference: 112
于 2009-12-15T10:54:08.160 回答