简体   繁体   中英

How to get get a month and date in Objective C?

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

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

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]; //

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM