如何在遥远的过去,BC时代创造一个特定的日期

all*_*loy 6 cocoa nsdate nsdatecomponents

我正试图在不列颠哥伦比亚省时代建立一个约会,但是很难失败.以下返回'4713'作为年份,而不是'-4712':

  NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents *components = [NSDateComponents new];
  [components setYear: -4712];
  NSDate *date = [calendar dateFromComponents:components];
  NSLog(@"%d", [[calendar components:NSYearCalendarUnit fromDate: date] year]);
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么吗?

更新:工作代码

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [NSDateComponents new];
    [components setYear: -4712];
    NSDate *date = [calendar dateFromComponents:components];
    NSDateComponents *newComponents = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit fromDate:date];
    NSLog(@"Era: %d, year %d", [newComponents era], [newComponents year]);
Run Code Online (Sandbox Code Playgroud)

正如本解释的那样,这为时代打印0.

Ben*_*itz 6

你的代码实际上工作正常.由于没有零年,-4712是公元前4713年.如果您检查时代组件,您将看到它为零,在公历中表示BC.翻转那个负号,你会看到4712 AD(时代1).