alloy
alloy

Reputation: 21048

How to create a specific date in the distant past, the BC era

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.

Upvotes: 6

Views: 1644

Answers (1)

Ben Stiglitz
Ben Stiglitz

Reputation: 4004

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).

Upvotes: 6

Related Questions