简体   繁体   English

如何获得目标C中的月份和日期?

[英]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. 我是目标C的新手,我正在开发一个应用程序,以确定用户输入年份和天数时的出生日期。 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 ? 例如,如果用户输入1985作为他/她的出生年,而天数是311。他/这里的出生日期是1985年11月6日。那么如何从1985年的311中获得11月6日呢? Please help 请帮忙

You should never have to calculate whether the current year is a leap year or not. 永远不必计算当前年份是否是a年。 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). 为了回答您的问题,您可以使用一个数组来存储每个月末{31,28,31,30,...}的天数,并将其用作参考(将总和减去一个循环)。 You'll also have to check if the year was a leap year and subtract one from the total if its over 59. 您还必须检查年份是否为a年,如果年份超过59,则将其减去。

You don't need anything specific from Objective-C... first you need to know if the year is a leap year . 您不需要Objective-C的任何特定功能...首先,您需要知道年份是否是a年 Then you need to count the days from the months until you end with your target day. 然后,您需要计算从月份开始直到完成目标日期为止的日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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