DateFormatter dateFromString Always Returns nil in swift 3

Viewed 9300

Due to some reason fail to convert a string to a NSDate.

This is my date converting code:

 let kSQLiteDateFormat : String = "yyyy/MM/dd HH:mm:ss Z"
let dateFormat = [kSQLiteDateFormat,
"dd MM, yyyy",
"MMM-yyyy",
"yyyy-MM-dd",
"yyyy-12",
"yyyy/MM/dd",
"yyyy/mm/dd",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss Z",
"yyyy-MM-dd HH:mm:ss K",
"yyyy-MM-dd HH:mm:ss ZZ",
"yyyy/MM/dd hh:mm a",
"MM/dd/yyyy",
"MM/dd/yyyy HH:mm:ss Z",
"h:mm a",
"hh:mm a",
"yyyy/MM/dd HH:mm:ss Z",
"yyyy/MM/dd h:mm a",
"MM/dd/yyyy h:mm a",
"yyyy-MM-dd h:mm a",
"yyyy-MM-dd'T'hh:mm:ss",
"yyyy/MM/dd h a",
"yyyy-MM-dd'T'HH:mm:ss","dd MMM, yyyy","dd-MM-yyyy HH:mm", "EEE, MMM dd","MM/dd/yyyy hh:mm:ss a"]


if let dateString : String = dateString as String? {
        let dateFormatter : DateFormatter = DateFormatter()
        for format in dateFormat {

            dateFormatter.dateFormat =  format
            if  let date : NSDate = (dateFormatter.date(from: dateString)! as NSDate) {
                return date
            }
        }
    }
    return nil

every time return nil

3 Answers

I found if you choose to use format like "MM/dd/yyyy hh:mm:ss" instead of "MM/dd/yyyy HH:mm:ss", you will get nil if your hour great than 12. please notice the difference of the hh and HH .

so this format "MM/dd/yyyy HH:mm:ss" should work.

Related