views:

101

answers:

1

I’m trying to create a date in the BC era, but failing pretty hard. The following returns ‘4713’ as the year, instead of ‘-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]);

Any idea what I’m doing wrong?

UPDATE: Working code

    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]);

This prints 0 for the era, just as Ben explained.

+1  A: 

Your code is actually working fine. Since there’s no year zero, -4712 is the year 4713 BC. If you check the era component you’ll see that it’s zero, which in the Gregorian calendar indicates BC. Flip that negative sign and you’ll see 4712 AD (era 1).

Ben Stiglitz
I knew I was missing a piece of the puzzle :) Thanks a lot! (Added updated version of the code)
alloy