从出生日期提取的年龄始终不一致 [英] Age extracted from birth date always off by inconsistent amount
问题描述
我正在使用以下代码将用户提供的生日转换为当前日期的等效年份。多年来,输出始终不一致,而在几天和几个月中,输出总是非常大。
I'm using the following code to convert a user-supplied birthdate to its equivalent years from the current date. The output is always off by an inconsistent amount in years and very large numbers in days and months.
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc] init];
[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
NSDate *birthDate = [tempFormatter dateFromString:[NSString stringWithFormat:@"%@-%@-%@ 01:00:00",self.birthYear.text,self.birthMonth.text,self.birthDay.text]];
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthDate
toDate:now
options:0];
NSInteger years = [ageComponents year];
NSInteger days = [ageComponents day];
NSInteger months = [ageComponents month];
NSLog(@"Years: %ld, Days: %ld, Months: %ld",years,days, months);
输入 06-16-1986时输出的内容
以下
年份:28,天数:9223372036854775807,月份:9223372036854775807
Years: 28, Days: 9223372036854775807, Months: 9223372036854775807
年份减少1,而月份和日期产生的数字非常大。我在不同的日期都遇到同样的问题。例如, 12-07-1989
产生
The year is off by 1 and the months and days are producing extremely large numbers. I get the same issue using various dates. For example, "12-07-1989"
produces
年:25,天:9223372036854775807,月份:9223372036854775807
Years: 25, Days: 9223372036854775807, Months: 9223372036854775807
我在这里做什么错了?
推荐答案
问题出在这行上
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthDate
toDate:now
options:0];
如果您想要月份&要计算的天数,您需要将其包括在这样的组件中
if you want month & days to be calculated you need to include that in the components like this
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:( NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit)
fromDate:birthDate
toDate:now
options:0];
您的格式对于月份字符串也是错误的
also your format is wrong for month string
[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
应更正为
[tempFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
现在您将获得正确的日期。
now you will get correct date.
说明。苹果文档中提到的
是基于1的。因此,如果您不提供值,则会将1设置为默认值。因此,您之前的月份格式为 mm,并且未正确设置生日月份,因此为1986-01-16,所以现在为2014-04-01(在新加坡)。所以你得到28年是正确的。
explanation. as mentioned on apple documentation these are 1-based. so incase you dont provide a value it will put 1 as default. so earlier your month format was "mm" and it was not correctly setting a month for the birthday hence it was 1986-01-16 so now its 2014-04-01 (in singapore). So you get 28 years which is correct.
这篇关于从出生日期提取的年龄始终不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!