0

I am trying to compare a given date which is in string with today's date

func getDateFromDateString(date: String) -> Date {
      let dateFormatter = DateFormatter()
      dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
      dateFormatter.dateFormat =  "yyyy-MM-dd"//"yyyy-MM-dd'T'HH:mm:ssZ"
      let date = dateFormatter.date(from:date) ?? Date()
    return date
}


let ticketDate = getDateFromDateString(date: "2023-04-04")
        
let currentDate = Date()

if currentDate >  ticketDate {
  print("Expired")
} else {
  print("Active")
}

The result should be Active but it's Expired I don't know why

HangarRash
  • 7,314
  • 5
  • 5
  • 32

2 Answers2

1

Replace the line

if currentDate > ticketDate {

with

if Calendar.current.compare(currentDate, 
                            to: ticketDate, 
                            toGranularity: .day) == .orderedAscending {

it compares the dates ignoring less significant date components than day

vadian
  • 274,689
  • 30
  • 353
  • 361
0

Replaced code by these

func getDateFromDateString(dateString: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    let date = dateFormatter.date(from: dateString)
    return date
}

func todayDate() -> Date{
    let currentDate = Date()
    let calendar = Calendar.current

    let year = calendar.component(.year, from: currentDate)
    let month = calendar.component(.month, from: currentDate)
    let day = calendar.component(.day, from: currentDate)

    var dateComponents = DateComponents()
    dateComponents.year = year
    dateComponents.month = month
    dateComponents.day = day

    let date = calendar.date(from: dateComponents)!
    return date
}

let currentDate = todayDate()

let ticketDate = getDateFromDateString(dateString: "2023-04-04")!

if ticketDate >= currentDate {
    print("Active")
} else {
    print("Expired")
}

On your code current date have time as well so please remove time from today date. So it's compare with time which it will found greater and print as Expired. For better solution please use full date i.e. with time. If you want to know more please comment. I am happy to explain.

Amrit Tiwari
  • 922
  • 7
  • 21
  • 1
    You can replace the function `todayDate()` with the built-in function [startOfDay(for:)](https://developer.apple.com/documentation/foundation/calendar/2293783-startofday) – Joakim Danielson Apr 04 '23 at 08:16