我有两个 NSDate 对象,我想要两者之间的区别,结果应该还是一个 NSDate 对象。知道如何实现这一目标吗?
在这里,我试图解决一个独特的问题,我必须找出经过的时间,然后定位经过的时间。如果我在 NSDate 对象中有经过的时间,我可以对其进行本地化。所以想创建一个 NSDate 对象,它的时间分量与两个日期之间的时间间隔相同,这样我就可以使用 NSDateFormatter 来本地化它。
NSDate
表示时间实例,因此将 interval 时间表示为 NSDate
没有意义。你要的是NSDateComponents
:
NSDate *dateA;
NSDate *dateB;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
fromDate:dateA
toDate:dateB
options:0];
NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
如果从 05/05/2002 中减去 12/12/2001 会是哪一天?两个日期之间的时间间隔不可能是日期,它总是某种间隔。您可以使用 timeIntervalSinceDate: 来计算时间间隔。
要本地化,您可以尝试以下步骤:
您可以将 NSCalendar 与 dateFromComponents 一起使用:传入一个 NSDateComponents。
要将 timeInterval 分解为 NSDateComponents 看看 How do I break an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?.
最后使用 NSDateFormatter 和 initWithDateFormat:allowNaturalLanguage: 来获取您的本地化字符串。 Date Format String Syntax 显示了不同的占位符。
从
NSDate
类参考,你有实例方法来做这些-
isEqualToDate:
timeIntervalSinceDate:
您可以使用
NSDate
的timeIntervalSinceDate:
计算两个日期之间的时间间隔,但是将时间间隔表示为日期对您来说没有任何意义。
在 NSDate 中使用 -compare: 有一个简单的方法:
NSDate *dateA = [NSDate dateWithTimeIntervalSinceNow:100];
NSDate *dateB = [NSDate dateWithTimeIntervalSinceNow:200];
NSDate *myDate = [NSDate dateWithTimeIntervalSinceNow:150];
NSArray *dateArray = [NSArray arrayWithObjects:dateA, dateB, myDate, nil];
NSArray *sortedArray = [dateArray sortedArrayUsingSelector:@selector(compare:)];
if ([myDate isEqualToDate:[sortedArray objectAtIndex:1]])
NSLog(@"myDatea between dateA and dateB");