小编典典

使用Swift中的NSDateComponents从出生日期开始计算年龄

swift

我正在尝试使用此功能从Swift中的BirthdayDate计算年龄:

var calendar : NSCalendar = NSCalendar.currentCalendar()

var dateComponentNow : NSDateComponents = calendar.components(
             NSCalendarUnit.CalendarUnitYear, 
             fromDate: birthday, 
             toDate: age, 
             options: 0)

但我得到一个错误 Extra argument toDate in call

在目标c中,这是代码,但我不知道为什么会收到此错误:

NSDate* birthday = ...;

NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar] 
                               components:NSYearCalendarUnit 
                               fromDate:birthday
                               toDate:now
                               options:0];
NSInteger age = [ageComponents year];

有比这更好的正确形式吗?


阅读 767

收藏
2020-07-07

共1个答案

小编典典

您收到一条错误消息,因为0它不是的有效值NSCalendarOptions。对于“无选项”,请使用NSCalendarOptions(0)或简单地nil

let ageComponents = calendar.components(.CalendarUnitYear,
                              fromDate: birthday,
                                toDate: now,
                               options: nil)
let age = ageComponents.year

(指定nil是可能的,因为它NSCalendarOptions符合RawOptionSetType从继承的协议NilLiteralConvertible。)

Swift 2更新:

let ageComponents = calendar.components(.Year,
    fromDate: birthday,
    toDate: now,
    options: [])

Swift 3更新:

假设使用Swift 3类型DateCalendar

let now = Date()
let birthday: Date = ...
let calendar = Calendar.current

let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
2020-07-07