简体   繁体   中英

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.

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)
    }
}

Swift 3 & 4:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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