使用两个NSDates计算人的年龄 [英] Calculating the age of a person using two NSDates
问题描述
代表某人的班级有一种方法来计算该人的年龄:
My class representing a person has a method to calculate that person's age:
@interface Student : NSObject
@property (strong) NSDate *dob;
// This method will work out the person's age in calendar years
- (NSDateComponents*)ageCalculation:(NSDate*)dob;
这是类实现文件
@implementation Student
- (NSDateComponents*)ageCalculation:(NSDate*)dob {
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [calendar components:units
fromDate:dob
toDate:now
options:0];
return components;
}
@end
我不确定我正在这样做:
I'm not sure that I'm doing this right, though:
Student *student1 = [[Student alloc] init];
[student1 setDob:aDateOfBirth];
NSDateComponents *ageComponents = [student1 ageCalculation:aDateOfBirth];
我该如何处理这个方法的结果?如何使 ageCalculation:
使用我已经设置的日期?
What should I do with the result of this method? How can I make ageCalculation:
use the date I already set?
推荐答案
有几件事情可以注意到。首先,计算年龄的代码很好,除了我不明白为什么你返回 NSDateComponents
而不是年龄。
There are a couple of things that can be noted. First of all, the code for computing the age is fine, except that I don't understand why you return NSDateComponents
instead of just the age in years.
以下是我的操作方法
- (NSInteger)age {
NSDate *today = [NSDate date];
NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:self.dob
toDate:today
options:0];
return ageComponents.year;
}
您只对年
组件,因此返回它而不是 NSDateComponents
。使用 self.dob
而不是参数获取您之前设置的日期。
You are interested only in the year
component, so return it instead of NSDateComponents
. Using self.dob
instead of an argument gets the date you set earlier.
这篇关于使用两个NSDates计算人的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!