在 Swift 中使用 NSDateComponents 从出生日期计算年龄

人气:1,081 发布:2022-10-16 标签: swift nsdatecomponents

问题描述

我正在尝试使用此函数从 Swift 中的birthdayDate 计算年龄:

I am trying calculate the age from birthdayDate in Swift with this function:

var calendar : NSCalendar = NSCalendar.currentCalendar()

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

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

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

In objective c this was the code, but I don't know why get this error:

NSDate* birthday = ...;

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

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

Is there correct form better than this?

推荐答案

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

You get an error message because 0 is not a valid value for NSCalendarOptions. For "no options", use NSCalendarOptions(0) or simply nil:

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

(指定 nil 是可能的,因为 NSCalendarOptions 符合 RawOptionSetType 协议,该协议又继承了来自 NilLiteralConvertible.)

(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits from NilLiteralConvertible.)

Swift 2 更新:

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

Swift 3 更新:

假设使用了 Swift 3 类型 DateCalendar:

Assuming that the Swift 3 types Date and Calendar are used:

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

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

269