ios - NSDateFormatter 时间格式取决于 Locale

标签 ios swift 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:

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.

我发现它在我的设备(我在欧洲)上运行良好,但在美国设备和模拟器上不起作用,即使用户选择 12h 格式,它仍会返回 24h 格式。 我也曾尝试将我的地区更改为美国,但在我的设备上它仍然可以正常工作。

您发现我的代码有什么问题吗? 反正这个问题也是

最佳答案

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

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

关于ios - NSDateFormatter 时间格式取决于 Locale,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722309/

相关文章:

objective-c - NSDateFormatter 从字符串中返回不正确的日期

ios - 解析 : PFUser signUpInBackgroundWithBlock causing exception when trying to convert anonymous user to regular

ios - AudioFile 修剪不起作用

swift - INSearchForNotebookItemsIntent 未达到 IntentsUI 扩展

ios - "Downcasting"Swift 中的 C 结构

ios - 无法在单例类中初始化 CGFloat

iphone - NSDateFormatter 关闭一小时

ios - 如何检查某个对象是否存在于 NSMutableArray 的某个索引处?

ios - 视频作为 IOS Objective C 中的启动屏幕

ios - 使用 NSDateFormatter 或 mktime 创建格式化的 NSDate