问候,
最近我遇到了一个关于 NSCalendar 类的大问题(在我看来)。
在我的任务中,我需要处理从公元前 4000 年到公元 2000 年(公历)的大量时间段。在某些地方,我被迫以 100 年的间隔增加一些 NSDate。当在 AD 时间轴 (0->...) 中增加年份时,一切正常,但当我对 BC 尝试同样的事情时,我有点困惑。
问题是,当您尝试将 3000BC [edited] 年加 100 年时,无论如何您都会得到 3100BC [edited] ......我个人觉得这很奇怪且不合逻辑。正确结果应该是2900BC。
下面是代码示例,您可以看到这种“不正确”的行为:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
// initing
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setYear:-1000];
NSDate *date = [gregorian dateFromComponents:comps];
// math
NSDateComponents *deltaComps = [[[NSDateComponents alloc] init] autorelease];
[deltaComps setYear:100];
date = [gregorian dateByAddingComponents:deltaComps toDate:date options:0];
// output
NSString *dateFormat = @"yyyy GG";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:dateFormat];
NSLog(@"%@", [formatter stringFromDate:date]);
您对这种行为有何看法?这是它应该如何工作还是这是一个错误?我很困惑:S。
顺便说一句:方法 [NSCalendar components:fromDate:toDate:options:] 不允许我们计算 BC 时代的年份之间的差异...额外的“为什么?”在这个潘多拉的盒子里。
P.S.:我正在研究官方文档和其他资源,但没有发现任何关于这个问题的信息(或者它可能是为了工作而我是个白痴?)。
最佳答案
我找到了解决此错误的简单方法。 在这里:
@interface NSCalendar (EraFixes)
- (NSDate *)dateByAddingComponentsRegardingEra:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts;
@end
@implementation NSCalendar (EraFixes)
- (NSDate *)dateByAddingComponentsRegardingEra:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts
{
NSDateComponents *toDateComps = [self components:NSEraCalendarUnit fromDate:date];
NSDateComponents *compsCopy = [[comps copy] autorelease];
if ([toDateComps era] == 0) //B.C. era
{
if ([comps year] != NSUndefinedDateComponent) [compsCopy setYear:-[comps year]];
}
return [self dateByAddingComponents:compsCopy toDate:date options:opts];
}
@end
如果你想知道为什么我只反转年份,答案很简单,除了年份之外的所有其他组件都以正确的方式递增和递减(我没有测试它们,但几个月和几天似乎工作正常)。
编辑:删除了错误添加的自动释放,谢谢约翰。
关于objective-c - BC时代的NSCalendar问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3719247/