Home > Net >  How to get age using Date()
How to get age using Date()

Time:11-22

Using Xcode 14.1 and Swift

I am trying to recreate an app from Github and i am stuck on this code which gets age in years using Date():

var age: Int {
  return Date().years(from: birthDate)
}

The above code returns an error:

Value of type 'Date' has no member 'years'

How can I fix this?

EDIT:

FirestoreUser.swift:

import Foundation
import FirebaseFirestoreSwift

public struct FirestoreUser: Codable, Equatable {
    @DocumentID var id: String?
    let name: String
    let birthDate: Date
    let bio: String
    let isMale: Bool
    let orientation: Orientation
    let pictures: [String]
    let liked: [String]
    let passed: [String]
    
    var age: Int {
        Date().years(from: birthDate)
    }

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case birthDate
        case bio
        case isMale = "male"
        case orientation
        case picturesv
        case liked
        case passed
    }
}

public enum Orientation: String, Codable, CaseIterable{
    case men, women, both
}

MatchModel.swift:

import UIKit

struct MatchModel: Identifiable{
    let id: String
    let userId: String
    let name: String
    let birthDate: Date
    let picture: UIImage
    let lastMessage: String?
    
    var age: Int{
        Date().years(from: birthDate)
    }
}

CodePudding user response:

There is probably an extension of Date missing which does the date math with Calendar.

It's just one line. Replace

return Date().years(from: birthDate)

with

Calendar.current.dateComponents([.year], from: from, to: .now).year!

Or as Date extension

extension Date {
    func years(from: Date) -> Int {
        Calendar.current.dateComponents([.year], from: from, to: self).year!
    }
}
  • Related