Search code examples
iosswiftnsdateformatter

iOS correct dateFormat for "Optional(1),Optional(19),Optional(2017)"


let dateStr1 = "1:19:2017" // Type one
let dateStr2 = "1,19,2017" // Type two
let dateStr3 = "(1)(19)(2017)" // Type three
let dateStr4 = "Optional(1),Optional(19),Optional(2017)"

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "mm:dd:yyyy"
let date1 = dateFormatter.date(from: dateStr1)
// ouput: Jan 19, 2017, 12:01 AM

dateFormatter.dateFormat = "mm,dd,yyyy"
let date2 = dateFormatter.date(from: dateStr2)
// ouput: Jan 19, 2017, 12:01 AM

dateFormatter.dateFormat = "(mm)(dd)(yyyy)"
let date3 = dateFormatter.date(from: dateStr3)
// ouput: Jan 19, 2017, 12:01 AM

dateFormatter.dateFormat = ? // what would be correct formatted string
let date4 = dateFormatter.date(from: dateStr4)
// ouput: nil

Now my question is that what would be the correct date format for dateStr4. I know I can do this by removing Optional substring from that string. But I don't want to do that. I just want to know what should be the correct formatted string?


Solution

  • Correct dateFormat is:

    dateFormater.dateFormat = "'Optional'(mm),'Optional'(dd),'Optional'(yyyy)"
    

    Output: 2017-01-18 18:01:00 +0000