let birthday = NSCalendar.currentCalendar().dateWithEra(1, year: 2016, month: 07, day: 25, hour: 8, minute: 53, second: 0, nanosecond: 0)!
func calculateAge(birthday: NSDate) -> String {
func grammaticalString(forUnit unit: String, value: Int) -> String {
if value > 1 {
return "\(value) \(unit)s"
} else {
return "\(value) \(unit)"
}
}
let calendar = NSCalendar.currentCalendar()
let unitFlags: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute]
let ageComponent = calendar.components(unitFlags, fromDate: birthday, toDate: NSDate(), options: [])
let years = ageComponent.year
let months = ageComponent.month
let days = ageComponent.day
let hours = ageComponent.hour
switch (years, months, days, hours) {
case (let y, let m, _, _) where y > 0:
return "\(grammaticalString(forUnit: "Year", value: y)) \(grammaticalString(forUnit: "Month", value: m))"
case (let y, let m, let d, _) where y == 0 && m > 0:
return "\(grammaticalString(forUnit: "Month", value: m)) \(grammaticalString(forUnit: "Day", value: d))"
case (let y, let m, let d, _) where y == 0 && m == 0 && d > 0:
return "\(grammaticalString(forUnit: "Day", value: d))"
case (let y, let m, let d, let h) where y == 0 && m == 0 && d == 0 && h > 0:
return "\(grammaticalString(forUnit: "Hour", value: h))"
case (let y, let m, let d, let h) where y == 0 && m == 0 && d == 0 && h == 0:
if ageComponent.minute > 0 {
return "\(grammaticalString(forUnit: "Minute", value: ageComponent.minute))"
} else {
return "-"
}
default:
return "-"
}
}
// Output will be any of these
// 2 Years 3 Months
// 3 Months 0 Days
// 2 Days
// 3 Hours
// 45 Minutes
// -