Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Created November 16, 2023 22:56
Show Gist options
  • Save lucianoschillagi/ee879cfb5be85a8b352edcb2249e42e3 to your computer and use it in GitHub Desktop.
Save lucianoschillagi/ee879cfb5be85a8b352edcb2249e42e3 to your computer and use it in GitHub Desktop.
How many years are you lived?
import SwiftUI
struct DaysLived: View {
@State private var userBirthday = ""
@State private var userDaysLived: Int?
@State private var birthdate: Date?
@State private var wrongDateFormat = false
let alertMessage = """
Out of range or
Invalid date format,
please write yyyy-MM-dd
"""
var body: some View {
ZStack {
Color.cyan.opacity(0.3).ignoresSafeArea()
VStack {
TextField("Write your birthday", text: $userBirthday)
.font(.system(size: 36))
.bold()
Spacer()
Text("You have lived").font(.title)
Text(String(userDaysLived ?? 0))
.font(.system(size: 100, weight: .bold))
.foregroundColor(.black)
Text("days until now").font(.title)
Spacer()
Button("How many days you lived") {
userDaysLived = daysLivedCalculation(userBirthday: userBirthday)
}
.buttonStyle(.borderedProminent).font(.title2).foregroundColor(.white)
}
.bold()
.foregroundColor(.blue)
.fontDesign(.rounded)
.padding(25)
.alert(alertMessage, isPresented: $wrongDateFormat) {
Button("OK", role: .cancel) {
self.userDaysLived = 0
}
}
}
}
func daysLivedCalculation(userBirthday: String) -> Int {
// Date Formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let birthdate = dateFormatter.date(from: userBirthday) {
self.birthdate = birthdate
} else {
self.userBirthday = ""
self.wrongDateFormat = true
}
// Current Date
let currentDate = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.day], from: birthdate ?? Date.now, to: currentDate)
if let days = components.day {
return days
} else {
return 0
}
}
}
#Preview {
DaysLived()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment