【问题标题】:Proper construction of dateFormat to parse time using DateFormatter in Swift 3.1在 Swift 3.1 中使用 DateFormatter 正确构建 dateFormat 以解析时间
【发布时间】:2017-03-06 20:19:31
【问题描述】:

我在构建 dateFormat 以解析预定义格式的时间时使用了错误的文档。 maddy(下)提供了正确文档的链接。

这是我使用错误格式时发生的情况:

var idf = DateFormatter()
idf.locale = Locale(identifier: "en_US")
idf.dateStyle = .none
idf.dateFormat = "hh:MM:SSa"

// Of the variables defined here, the only one that doesn't cause an error 
// is the last one:
var sMidnight: String = "12:00:00AM"
var sEarly: String = "12:40:22AM"
var sMorning: String = "6:00:00AM"
var sNoon: String = "12:00:00PM"
var sAfternoon: String = "12:30:22PM"
var sEvening: String = "7:05:45PM"

// Put any of the variables besides sEvening here and you get a crash.
// "fatal error: unexpectedly found nil while unwrapping an Optional value"
var date: Date = idf.date(from: sEvening)!

print(idf.string(from: date)) // prints 07:05:45 PM

【问题讨论】:

  • 请参阅有关格式说明符的文档。你用错了。

标签: ios swift dateformatter


【解决方案1】:

MM 是两位数的月份编号。 SS 是小数秒。请查看与格式说明符相关的the documentation

你想要:

"h:mm:ssa"

适合您的格式。

【讨论】:

  • 谢谢。我无法找到正确的文档。这解决了问题。
  • 很高兴为您提供帮助。请不要忘记接受可以解决您问题的答案。您似乎还没有回答任何问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多