dateFormater returns nil on Specific date

Hi, A client of our App as reported an issue that is date of birth is not right on the app. as we checked the bug we have notice that this specific dates fail parsing from string to date.

the following String always fail "1991-03-24'T'00:00:00"

  class func convertStringToDate(DateString : String) -> Date

    {

        let dateFormatter : DateFormatter = DateFormatter()

        dateFormatter.locale = Locale(identifier: "en_US_POSIX")

        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

        if  let date = dateFormatter.date(from: (DateString)) {

            

            return date;

        }

        return Date()

    }

Please Help.

Do you really run this in playground ?

Your date string is wrong: do not include ' before and after T

This works:

let birth = "1991-03-24T00:00:00"
func convertStringToDate(dateString : String) -> Date {
        let dateFormatter : DateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = TimeZone(identifier: "UTC") // Need to define TimeZone
        if let date = dateFormatter.date(from: dateString) {  // No parenthesis needed here around dateString
            return date
        }
        return Date()
    }
let birthDate = convertStringToDate(dateString: birth)
print("birthDate", birthDate)

.

And gives:

birthDate 1991-03-24 00:00:00 +0000

Notes:

  • labels as DateString should start with lowercase
  • You need to define TimeZone, otherwise you may get a different result depending on your locale

If you get the String with single quoted T,

let birth = "1991-03-24'T'00:00:00"

you have 2 options:

  • remove the single quotes
var birth = "1991-03-24'T'00:00:00"
birth = birth.replacingOccurrences(of: "'", with: "")
  • change the dateFormat, by adding single quote (ned to escape it, hence '' before and after 'T' as:
        dateFormatter.dateFormat = "yyyy-MM-dd'''T'''HH:mm:ss"

I could have found a few timezones where date(from:) returns nil for "1991-03-24T00:00:00". For example, Asia/Jerusalem.

I'm not sure what would be the reason for this specific case, but historically, some ranges of local date & time may be missing from the calendar system of some regions.

You may need to find a better way to represent a date using Date for such regions.

dateFormater returns nil on Specific date
 
 
Q