Search code examples
swiftdateswiftuicompare

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()
            }
}
}

Solution

  • 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 {
                    // ...
                }