简体   繁体   English

NSDateFormatter时间格式取决于语言环境

[英]NSDateFormatter time format depending on Locale

I'm experiencing a really strange issue that sounds more like a system bug. 我遇到了一个非常奇怪的问题,听起来像是系统错误。 I want to format a date using only Hour and Minute information and, if necessary, display AM/PM. 我只想使用小时和分钟信息来格式化日期,并在必要时显示AM / PM。

Here is my code: 这是我的代码:

extension NSDate {

    func localizedStringTime()->String {

        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale.currentLocale()
        dateFormatter.dateFormat = "HH:mm"
    }
}

As you can see i'm using HH and not hh and as stated on Apple documentation it should automatically add AM/PM if user chooses 12h format: 如您所见,我使用的是HH而不是hh并且如Apple文档所述,如果用户选择12h格式,它应该自动添加AM / PM:

The representation of the time may be 13:00. 时间的表示可能是13:00。 In iOS, however, if the user has switched 24-Hour Time to Off, the time may be 1:00 pm. 但是,在iOS中,如果用户将24小时制切换为关闭,则时间可能是1:00 pm。

I found that it works perfectly on my Device (I'm based in Europe) but it doesn't work on USA Devices and on Simulator, where even if user selects 12h format it still returning the 24h format. 我发现它可以在我的设备(我位于欧洲)上完美运行,但是在美国设备和模拟器上却无法运行,即使用户选择了12h格式,它仍然会返回24h格式。 I've also tried to change my Region to United State but from my device it still work correctly. 我还尝试将“地区”更改为“美国”,但是从我的设备上,它仍然可以正常工作。

Do you see any problem with my code? 您看到我的代码有任何问题吗? Anyway, this problem is also 反正这个问题也是

You can use the localized string from date function like this... 您可以像这样使用date函数中的本地化字符串...

extension NSDate {
    func localizedStringTime()->String {
        return NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.ShortStyle)
    }
}

Swift 3 & 4: Swift 3和4:

extension Date {
  var localizedStringTime: String {
    return DateFormatter.localizedString(from: self, dateStyle: .none, timeStyle: .short)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM