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
The forced unwrapping in
if let date : NSDate = (dateFormatter.date(from: dateString)! as NSDate) {
return date
}
makes the program crash if dateString
does not match the date format and dateFormatter.date(from: dateString)
returns nil
.
What you probably want is
if let date = dateFormatter.date(from: dateString) {
return date
}
or, if you really need an NSDate
and not a Date
:
if let date = dateFormatter.date(from: dateString) {
return date as NSDate
}
In addition, you might want to set the formatter's locate to "POSIX"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
in order to avoid a dependency on the user's regional preferences, compare DateFormatter doesn't return date for "HH:mm:ss".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With