我从出生日期就无法找到年龄。我得到的是
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
我的代码
override func viewDidLoad() {
super.viewDidLoad()
var dateString = user.birthday
var dateFormatter = NSDateFormatter()
// this is imporant - we set our input date format to match our input string
dateFormatter.dateFormat = "dd-MM-yyyy"
// voila!
var dateFromString = dateFormatter.dateFromString(dateString)
let age = calculateAge(dateFromString!)
}
func calculateAge (birthday: NSDate) -> NSInteger {
var userAge : NSInteger = 0
var calendar : NSCalendar = NSCalendar.currentCalendar()
var unitFlags : NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay
var dateComponentNow : NSDateComponents = calendar.components(unitFlags, fromDate: NSDate())
var dateComponentBirth : NSDateComponents = calendar.components(unitFlags, fromDate: birthday)
if ( (dateComponentNow.month < dateComponentBirth.month) ||
((dateComponentNow.month == dateComponentBirth.month) && (dateComponentNow.day < dateComponentBirth.day))
)
{
return dateComponentNow.year - dateComponentBirth.year - 1
}
else {
return dateComponentNow.year - dateComponentBirth.year
}
}
答案 0 :(得分:23)
更新: Xcode 8.2.1•Swift 3.0.2
extension Date {
var age: Int {
return Calendar.current.dateComponents([.year], from: self, to: Date()).year!
}
}
let myDOB = Calendar.current.date(from: DateComponents(year: 1970, month: 9, day: 10))!
let myAge = myDOB.age // 46
Xcode 7.2•Swift 2.1.1
您可以使用NSCalendar方法组件来计算从特定日期到今天的年数,如下所示:
extension NSDate {
var age: Int {
return NSCalendar.currentCalendar().components(.Year, fromDate: self, toDate: NSDate(), options: []).year
}
}
let myDOB = NSCalendar.currentCalendar().dateWithEra(1, year: 1970, month: 09, day: 10, hour: 0, minute: 0, second: 0, nanosecond: 0)!
let myAge = myDOB.age // 46
答案 1 :(得分:2)
重要:强>
必须设置时区以创建UTC出生日期,否则时区之间会出现不一致。
Swift 3
extension Date {
//An integer representation of age from the date object (read-only).
var age: Int {
get {
let now = Date()
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: self, to: now)
let age = ageComponents.year!
return age
}
}
init(year: Int, month: Int, day: Int) {
var dc = DateComponents()
dc.year = year
dc.month = month
dc.day = day
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
if let date = calendar.date(from: dc) {
self.init(timeInterval: 0, since: date)
} else {
fatalError("Date component values were invalid.")
}
}
}
用法:
let dob = Date(year: 1975, month: 1, day: 1)
let age = dob.age
print(age)
答案 2 :(得分:0)
在Swift 2.0+时代,计算代码看起来应该是这样的:
extension NSDate {
var age:Int {
return NSCalendar.currentCalendar()
.components(NSCalendarUnit.Year,
fromDate: self,
toDate: NSDate(),
options: NSCalendarOptions(rawValue: 0)
.year
}
}
答案 3 :(得分:-1)
只需使用DateTools窗格即可。绝对是最简单的方法。 https://github.com/MatthewYork/DateTools
对于Swift 3
import DateTools
let birthday: Date = ....
let ageString = String((Date() as NSDate).years(from: birthday))