0

I need to convert Julian dates (fetched from the API) to Gregorian dates. I followed the following link: Converting a Gregorian date to Julian Day Count in Objective C. But, the year component comes confusing by both ways (1):

NSInteger julianDays = 1580198400;
NSUInteger julianDayFor01012000 = 2451545;
NSCalendar *cal = [[NSCalendar alloc]           initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2000;
comp.month = 1;
comp.day = 1;
NSDate *ref = [cal dateFromComponents:comp];
NSDateComponents *diff = [[NSDateComponents alloc] init];
diff.day = julianDays - julianDayFor01012000;
NSDate *date = [cal dateByAddingComponents:diff toDate:ref options:0];
comp = [cal components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:date];

Output: Calendar Year: 4321724 Month: 3 Leap month: no Day: 3

And (2):

NSInteger julianDays = 1580198400;
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"g"];
NSDate *date = [fmt dateFromString:[@(julianDays) stringValue]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [cal components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:date];

Output: Calendar Year: 4321724 Month: 3 Leap month: no Day: 3

Why is the year coming as 4321724? Do I have to interpret it further? Any help would be appreciated.

Ghazalah
  • 233
  • 2
  • 14
  • Is `julianDays` correct initialised? 1580198400 equals 4329310 Years. – ivion Jan 07 '19 at 09:56
  • @ivion Well, this is what I am getting from the API, and I was expecting them to convert to some date in the present or near future that I could have understood. But, since you indicated I verified this by converting this date directly online and it correctly converts it to 4329310 only. Thank man! I will talk to the backend team regarding this. – Ghazalah Jan 07 '19 at 10:27
  • You could perhaps also give us the contents of the API response, because julianDays and julianDayFor01012000 are not the same measure (one is about 644 times bigger than the other), and neither represents a number of days since another date (2451545 days = 6716 years). I'd reconsider the nature of those values before going deeper in the code. – il3v Jan 08 '19 at 14:33

0 Answers0