问题
I have this simple code:
let string = "2017-02-23 15:26:00";
let df = DateFormatter();
df.dateFormat = "yyyy-MM-dd hh:mm:ss";
let result = df.date(from: string);
The result is nil. Why?
回答1:
Your date is 24 hour format So it should be HH
not hh
, so change your date formate to yyyy-MM-dd HH:mm:ss
.
let string = "2017-02-23 15:26:00"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let result = df.date(from: string)
回答2:
let string = "2017-02-23 15:26:00";
let df = DateFormatter();
df.dateFormat = "yyyy-MM-dd HH:mm:ss";
let result = df.date(from: string);
来源:https://stackoverflow.com/questions/42502568/why-i-cant-convert-string-to-date-in-swift