I'm trying to parse String to date but getting nil value for some specific date.
The parsing of 2017-04-21 09:00:00
Tis successfully, but getting nil value for string 2017-05-30 23:00:00
.
Here my code:
func checkingDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
let now = Date()
if let currentData = dateObj {
if (currentData >= now) {
print("big")
return true
} else if currentData < now {
print("small")
return false
}
}
return false
}
Thanks in advance
You're using hh
as the hours specifier. That's a 12-hour value, and "23" clearly falls outside that range. ("09" parses because it's in range.)
Use HH
instead:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
See more on this question at Stackoverflow