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
@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
A quick and simple approach is to use
DateFormatter
and luckily SwiftUIText
View supports it:The code would look like this:
Text("(birthdate)")
toText(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 itTo calculate somebody’s age from their birthday, you can use code like this: