1

I am a new to objective C, I am developing a app to determine the date of birth when user gives the year and the number of days. For example if user give 1985 as his/her year of birth and the number of days as 311. his/here date of birth is 1985 November 6. So how to get the November 6 from 311 in 1985 ? Please help

4 Answers4

4

You should never have to calculate whether the current year is a leap year or not. Never ever ever. Let the frameworks do that for you. People much more intelligent than you or I have done this for us already, so why on earth would we go about re-inventing this wheel with sub-optimal algorithms that would never account for all of the intricate calendar variations?

It's stupid to do this yourself. So don't:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *startComponents = [[NSDateComponents alloc] init];
[startComponents setYear:1985];
[startComponents setDay:311];

NSDate *date = [gregorian dateFromComponents:startComponents];

NSLog(@"endDate: %@", date);

This logs:

endDate: 1985-11-07 08:00:00 +0000
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
-1

Something like this (not tested):

NSDateFormatter *df = [[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"yyyy"];
NSDate *date1 = [df dateWithString:@"1985"];
NSDate *date2 = [df dateByAddingTimeInterval:60*60*24*311]; //
Kreiri
  • 7,840
  • 5
  • 30
  • 36
-2

First off, why are you getting the number of days from someone instead of getting the month and day. Users will not know what day of the year they are born and will be frustrated to try and figure it out.

To answer your question, you could have an array that stores the number of days at the end of each month {31, 28, 31, 30, ...} and use that as a reference (subtracting the total in a loop). You'll also have to check if the year was a leap year and subtract one from the total if its over 59.

RileyE
  • 10,874
  • 13
  • 63
  • 106
  • 1
    -1 This is wrong. You should use the built-in APIs to do this. – Dave DeLong May 18 '12 at 18:09
  • In Sri Lanka National Identification Numbers are like this - 853110035. So the first digits are the birth year and next three digits are the number of days to the birthday from january 1st. – Amith Sanjeewa Ranasinghe May 18 '12 at 18:15
  • This isn't wrong. And why are the API calls necessary? They are heavy for something as simple as this. They have to process a lot more to come up with the same answer. – RileyE May 18 '12 at 18:28
-2

You don't need anything specific from Objective-C... first you need to know if the year is a leap year. Then you need to count the days from the months until you end with your target day.

Community
  • 1
  • 1
Santiago V.
  • 1,088
  • 8
  • 24