NSDateFormatter时间格式取决于语言环境 [英] NSDateFormatter time format depending on Locale

查看:204
本文介绍了NSDateFormatter时间格式取决于语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常奇怪的问题,听起来更像是系统错误. 我只想使用小时和分钟信息来格式化日期,并在必要时显示AM/PM.

这是我的代码:

extension NSDate {

    func localizedStringTime()->String {

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

您可以看到我使用的是HH而不是hh,并且如Apple文档所述,如果用户选择12h格式,它应该自动添加AM/PM:

时间的表示可能是13:00.但是,在iOS中,如果 用户已将"24小时制"设置为关闭",时间可能是1:00 pm.

我发现它可以在我的设备(我位于欧洲)上完美运行,但是在美国设备和模拟器上却无法运行,即使用户选择了12h格式,它仍然会返回24h格式. 我还尝试将地区"更改为美国",但是从我的设备上,它仍然可以正常工作.

您看到我的代码有任何问题吗? 无论如何,这个问题也是

解决方案

您可以像这样使用date函数中的本地化字符串...

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

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.

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:

The representation of the time may be 13:00. In iOS, however, if the user has switched 24-Hour Time to Off, the time may be 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. 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...

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

这篇关于NSDateFormatter时间格式取决于语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆