将facebook生日转换为年龄迅速

时间:2017-03-24 19:25:45

标签: swift facebook date converter

从Facebook SDK检索生日时,我收到此字符串“01/12/1990”。

我的问题是,您如何使用此字符串将生日转换为用户的年龄?

3 个答案:

答案 0 :(得分:2)

Swift 4

我的用例也适用于Facebook,我使用UserDefaults来存储生日。以下函数将从UserDefaults中检索birthdate,由graphRequest返回,其格式与Date相同。该函数将返回一个具有用户年龄的Integer。

    func getAgeFromBirthdate() -> Int {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    let birthday = UserDefaults.standard.object(forKey: "birthday")
    let birthdayString = birthday as! String
    let birthdate = dateFormatter.date(from: birthdayString)
    let currentDate = Date()
    let calendar: Calendar = Calendar(identifier: .gregorian)
    let age = calendar.component(.year, from: birthdate!).distance(to: calendar.component(.year, from: currentDate))
    return age
}

答案 1 :(得分:1)

 func yearsBetween(date1: Date, date2: Date) -> Int {
        let calendar = Calendar.current
        let components = calendar.dateComponents([Calendar.Component.year], from: date1, to: date2)
        return components.year ?? 0
    }

//获取年龄

    let dateString = "01/12/1990"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    let date1 = dateFormatter.date(from: dateString)
    let date2 = Date()
    let age  = self.daysBetween(date1:date1!, date2:date2)

希望它会对你有所帮助。

答案 2 :(得分:0)

您可以在询问之前再做一点Google,也可以找到这些答案:

How do you create a swift Date object

Calculate age from birth date using NSDateComponents in Swift

func calcAge(birthday:String) -> Int {
    let dateFormater = DateFormatter()
    dateFormater.dateFormat = "MM/dd/yyyy"
    let birthdayDate = dateFormater.date(from: birthday)
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
    let now: NSDate! = NSDate()
    let calcAge = calendar.components(.year, from: birthdayDate!, to: now as Date, options: [])
    let age = calcAge.year
    return age!
}

用法:

print(calcAge(birthday: "01/12/1990"))