我正在尝试使用下面的代码从字符串“07:00 PM”获取日期,但它总是返回我的nil。有什么帮助吗?
let hr12Formatter : NSDateFormatter = NSDateFormatter()
hr12Formatter.dateStyle = NSDateFormatterStyle.NoStyle
hr12Formatter.timeStyle = NSDateFormatterStyle.ShortStyle
hr12Formatter.dateFormat = "hh:mm a"
let hr12Date : NSDate = hr12Formatter.dateFromString(inputTimeString)!
答案 0 :(得分:2)
只需删除这两行日期和时间样式,保留dateFormat并将日期格式化程序区域设置为en_US_POSIX
Swift 3或更高版本
let formatter = DateFormatter()
formatter.defaultDate = Calendar.current.startOfDay(for: Date()) // add this if you would like to use todays date as default
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "hh:mm a"
let inputTimeString = "07:00 PM"
if let hr12Date = formatter.date(from: inputTimeString) {
print(hr12Date.description(with: .current))
}
答案 1 :(得分:0)
试试这个:
let timeString = "07:00 PM"
let hr12Formatter : NSDateFormatter = NSDateFormatter()
hr12Formatter.dateFormat = "hh:mm a"
let hr12Date : NSDate = hr12Formatter.dateFromString(timeString)!