web-dev-qa-db-ja.com

SwiftのNSDateComponentsを使用して、誕生日から年齢を計算します

私はこの関数でSwiftのbirthdayDateから年齢を計算しようとしています:

var calendar : NSCalendar = NSCalendar.currentCalendar()

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

しかし、エラーが発生しますExtra argument toDate in call

Objective Cではこれがコードでしたが、なぜこのエラーが発生するのかわかりません:

NSDate* birthday = ...;

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

これよりも正しい形式がありますか?

33
user3745888

_0_はNSCalendarOptionsの有効な値ではないため、エラーメッセージが表示されます。 「オプションなし」の場合、NSCalendarOptions(0)または単にnilを使用します。

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

nilNSCalendarOptionsから継承するRawOptionSetTypeプロトコルに準拠しているため、NilLiteralConvertibleを指定できます。)

Swift 2 ::の更新

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

Swift 3:の更新

Swift 3つのタイプDateおよびCalendarが使用されると仮定します。

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

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

このメソッドを作成するのはとても簡単です。メソッドに誕生日を入れるだけで、AgeがIntとして返されます。

スイフト3

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

スイフト2

func calcAge(birthday: String) -> Int{
    let dateFormater = NSDateFormatter()
    dateFormater.dateFormat = "MM/dd/yyyy"
    let birthdayDate = dateFormater.dateFromString(birthday)
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let now: NSDate! = NSDate()
    let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
    let age = calcAge.year
    return age
}

使用法

print(calcAge("06/29/1988"))
17
Gal Mesika

Swift 4は正常に動作します

func getAgeFromDOF(date: String) -> (Int,Int,Int) {

    let dateFormater = DateFormatter()
    dateFormater.dateFormat = "YYYY-MM-dd"
    let dateOfBirth = dateFormater.date(from: date)

    let calender = Calendar.current

    let dateComponent = calender.dateComponents([.year, .month, .day], from: 
    dateOfBirth!, to: Date())

    return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}

let age  = getAgeFromDOF(date: "2000-12-01")

print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
3
Bola Ibrahim

これはSwift 3

let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
2
A. Pooja

これはSwift 3で動作しています。.

let now = NSDate()
    let calendar : NSCalendar = NSCalendar.current as NSCalendar
    let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
    let age = ageComponents.year!
    ageCalculated.text = String(age)

@Martin Rに感謝

これはSwift 5での最良の方法です

lazy var dateFormatter : DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }()

let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))
0
Simao Coutinho