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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With