Jiri Svec
Jiri Svec

Reputation: 147

swiftUI - Date Comparison

I need to compare 2 dates and if it is the same date, do something... (dd/MM to dd/MM only). I generate today's date, then set my own date and when compared, the same dates do not match. (When displaying each date (as Text), the result is the same. E.g. 10-04 and 10-04.)

struct eddEntryView : View { // ContentView

let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd-MM"
        return formatter
    }()

@State private var today = Date()

let specificDate: Date = {
    var components = DateComponents()
    components.day = 14
    components.month = 04
    let newDate = Calendar.current.date(from: components) ?? Date()
    return newDate
}()

var entry: Provider.Entry

var body: some View {
    HStack{
        VStack(alignment: .leading){
            if Calendar.current.isDateInToday(specificDate) // today is 14-04, specific date is set for 14-04, but it doesn't work
{
                Text("THE SAME: \(specificDate, formatter: dateFormatter)")
                    .font(.title)
                    .foregroundColor(Color(.label))
                    .bold()
                Spacer()
            } else {
                Text("Not the same day... \(specificDate, formatter: dateFormatter)")
                    .font(.title)
                    .foregroundColor(Color(.label))
                    .bold()
                Spacer()
            }
}
}

Upvotes: 0

Views: 1287

Answers (2)

LuLuGaGa
LuLuGaGa

Reputation: 14418

There is a function isDateInToday(Date) on Calendar. You could use it like this:

if Calendar.current.isDateInToday(dueDate) {
    //...
}

There is also a function that compares whether to date fall on the same day:

Calendar.current.isDate(today, inSameDayAs: dueDate)

Upvotes: 2

Jiri Svec
Jiri Svec

Reputation: 147

Solution:

let today = Date() // Actual date
func formatDate(date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM"
    return formatter.string(from: date)
}

and then:

if ("\(formatDate(date: today))") .elementsEqual("14-04") // specific date {
                Text("the same: \(formatDate(date: today))")
                 // ... do something for the same day
                Spacer()
            } else {
                // ...
            }

Upvotes: -1

Related Questions