【问题标题】:swift NSDateFormatter not working快速 NSDateFormatter 不工作
【发布时间】:2014-09-04 04:05:31
【问题描述】:

我正在尝试如下格式化时间:

let formatter = NSDateFormatter()
formatter.dateFormat = "hh_mm_ss"
let d = formatter.stringFromDate(NSDate())
println("formatted text is: \(d)")

假设当前时间是 2014 年 9 月 3 日 22:15:30

  1. 当我在操场上运行此脚本时,它会以正确格式打印时间:22_15_30
  2. 在 AppDelegate 上运行时,它不会打印格式化的时间:22:15:30

我正在使用 xcode 6 beta 5... 我错过了什么吗?为什么 stringFromDate 不返回格式正确的日期?

编辑:我使用的是 xcode 6 beta 6。

谢谢!

【问题讨论】:

  • 非常适合我:formatted text is: 12_11_33 - 也许升级到 beta 7?
  • 按预期工作。
  • 24 小时格式是“HH”,而不是“hh”。
  • 感谢@MartinR,我将格式更改为“HH”,现在它打印出我所期望的。奇怪的是“hh”在操场上有效:S 请你回答这个问题,以便我标记为 OK?

标签: ios swift nsdate nsdateformatter


【解决方案1】:

24 小时格式是“HH”,而不是“hh”。

它在 Playground 中工作的原因可能是 用户定义的设置可以覆盖 12/24 格式的选择,比较 What is the best way to deal with the NSDateFormatter locale "feechur"?。 为了安全起见,请为日期格式化程序设置“en_US_POSIX”语言环境:

formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

// Swift 3:
formatter.locale = Locale(identifier: "en_US_POSIX")

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 2014-10-22
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多