我使用以下代码将用户提供的出生日期转换为当前日期的等效年份。输出在年份中的偏差总是不一致,而在天和月中的偏差则非常大。
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
年差 1,月份和日期产生的数字非常大。我使用不同的日期遇到同样的问题。例如,"12-07-1989"
产生
年:25,日:9223372036854775807,月:9223372036854775807
我在这里做错了什么?
问题出在这一行
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthDate
toDate:now
options:0];
如果您想要计算月份和日期,您需要将其包含在这样的组件中
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:( NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit)
fromDate:birthDate
toDate:now
options:0];
另外,您的月份字符串格式也是错误的
[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
应更正为
[tempFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
现在您将获得正确的日期。
解释。
正如苹果文档中提到的,这些是基于 1 的。因此,如果您不提供值,它将把 1 作为默认值。所以早些时候你的月份格式是“mm”,并且没有正确设置生日月份,因此它是 1986-01-16 所以现在是 2014-04-01 (在新加坡)。所以你得到了 28 年,这是正确的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)