Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 313
alloy Avatar asked Apr 27 '10 07:04

alloy


1 Answers

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

like image 132
Ben Stiglitz Avatar answered Oct 23 '22 04:10

Ben Stiglitz