skip to Main Content

I want to display the date that user chooses using the datepicker but it displays all the information and also i want to calculate the age but i dont really know how, now i solved the problem with displaying Date() but i cant really use the code to calculate age
BuildPreview

    @State var firstName = ""
    @State var lastName = ""
    @State var birthdate = Date()

var dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        
        return dateFormatter
    }()
    let age = Int()
    init() {
        let age = Calendar.current.dateComponents([.year], from: birthdate, to: Date())
            .year
    }

    var body: some View {
        Form{
            Section(header: Text("Personal data")){
                TextField("Enter first name", text: $firstName)
                TextField("Enter last name", text: $lastName)
                DatePicker("Birthdate", selection: $birthdate,in: ...Date(), displayedComponents:.date)
            }
            Section(header: Text("Final info")){
                HStack{
                    Image(systemName: "person.crop.circle")
                        .resizable()
                        .frame(width: 50, height: 50, alignment: .center)
                    Spacer()
                    VStack{
                        Text("(firstName) (lastName)")
                            .font(.headline)
                        Text("(birthdate)")
                            .font(.subheadline)
                    }
                    Spacer()
                    Image(systemName: "1.square.fill")
                        .resizable()
                        .frame(width: 50, height: 50)
                        .foregroundColor(.blue)
                }
                .padding(.horizontal ,10)
            }
        }
    }
}

2

Answers


  1. A quick and simple approach is to use DateFormatter and luckily SwiftUI Text View supports it:

    The code would look like this:

    // 1. Create a Dateformatter
    var dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        
        return dateFormatter
    }()
    
    1. Change : Text("(birthdate)") to Text(birthdate, formatter:dateFormatter)

    You can play with dateFormatter.dateStyle value to get the one you like, check out Set a datestyle in Swift, to read more about how you can play with it

    Login or Signup to reply.
  2. To calculate somebody’s age from their birthday, you can use code like this:

    let age = Calendar.current.dateComponents([.year], 
                                              from: birthday, 
                                              to: Date())
    .year
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search