Sauron Sauron - 6 months ago 11
iOS Question

Convert String to Date Returns nil for afternoon times only

I have the code to convert a string to a date as:

let dateString = detailData.value["eventStart"] as! String
print(dateString)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss Z" /*find out and place date format from http://userguide.icu-project.org/formatparse/datetime*/
let date = dateFormatter.dateFromString(dateString) // || date!.timeIntervalSince1970 >= presentDate.timeIntervalSince1970

print(date?.timeIntervalSince1970)


The output is:

2016-05-31 03:18:11 +0000
Optional(1464664691.0)

2016-06-03 14:00:44 +0000
nil

2016-06-01 00:38:08 +0000
Optional(1464741488.0)

2016-06-04 00:25:55 +0000
Optional(1464999955.0)

2016-05-31 22:19:54 +0000
nil


I see that the time in the afternoon (is 12+) return nil.

How can I prevent this?

Answer

Your date parsing is failing. In your case, its failing because of an invalid hour component in the input string.

Use 24-hour format HH instead of 12-hour format hh.

Comments