您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您收到一条错误消息,因为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类型DateCalendar

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

let ageComponents = calendar.dateComponents([.year], from: birthday, to: Now)
let age = ageComponents.year!
Swift 2022/1/1 18:17:37 有297人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶