无法将字符串解析为 iOS swift 中的日期类型 3
Unable to parse String to Date type in iOS swift 3
我正在尝试解析 String to date 但得到某个特定日期的 nil 值。
2017-04-21 09:00:00
的解析成功,但字符串 2017-05-30 23:00:00
.
的值为 nil
这是我的代码:
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
}
提前致谢
24 小时使用大写 H 小写 h 为 12 h
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
您正在使用 hh
作为小时说明符。这是一个 12 小时的值,“23”显然超出了该范围。 (“09”解析,因为它在范围内。)
改用HH
:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
您需要将日期格式更改为 yyyy-MM-dd HH:mm:ss。 HH用来表示24小时
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
}
我正在尝试解析 String to date 但得到某个特定日期的 nil 值。
2017-04-21 09:00:00
的解析成功,但字符串 2017-05-30 23:00:00
.
这是我的代码:
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
}
提前致谢
24 小时使用大写 H 小写 h 为 12 h
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
您正在使用 hh
作为小时说明符。这是一个 12 小时的值,“23”显然超出了该范围。 (“09”解析,因为它在范围内。)
改用HH
:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
您需要将日期格式更改为 yyyy-MM-dd HH:mm:ss。 HH用来表示24小时
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
}