3

How to check if the date is valid, before making a SQL query using

request.predicate = NSPredicate (format: "% @ <= AND myDate% @> = myDate" startDate, endDate)

an error occurs with the leap years, like 30 of February 2016.

// code form comment...
let startDate:NSDate = dateFormatter.dateFromString("2016-10-01")!
let endDate:NSDate = dateFormatter.dateFromString("2016-10-29")!
AndreLuisRomero
  • 67
  • 2
  • 10

2 Answers2

9

The return value of a date generated by DateFormatter's date(from:) method is an optional. If nil is returned the date is invalid, otherwise it's valid.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

if let date = dateFormatter.date(from:"2016-02-30") {
    print(date) // if this prints date is valid
}
else {
    print("Date is Invalid") // if this prints date is invalid
}

A Date cannot be instantiated with an invalid date string that is outside of the realm of real calendar dates.

If what you are asking is whether a date falls between two other dates, see here: https://stackoverflow.com/a/40057117/1694526

sketchyTech
  • 5,746
  • 1
  • 33
  • 56
0

Use DateFormatter class... It can be used to check any string whether it is a valid date or not and accordingly the string can be converted into nsdata.