使用Swift中的NSDateComponents从出生日期开始计算年龄
我正在尝试使用此功能从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];
有比这更好的正确形式吗?
回答:
您收到一条错误消息,因为0
它不是的有效值NSCalendarOptions
。对于“无选项”,请使用NSCalendarOptions(0)
或简单地nil
:
let ageComponents = calendar.components(.CalendarUnitYear, fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(指定nil
是可能的,因为它NSCalendarOptions
符合RawOptionSetType
从继承的协议NilLiteralConvertible
。)
let ageComponents = calendar.components(.Year, fromDate: birthday,
toDate: now,
options: [])
假设使用Swift 3类型Date
和Calendar
:
let now = Date()let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
以上是 使用Swift中的NSDateComponents从出生日期开始计算年龄 的全部内容, 来源链接: utcz.com/qa/425817.html