MatterGoal
MatterGoal

Reputation: 16430

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

Upvotes: 3

Views: 5047

Answers (2)

Teodor Ciuraru
Teodor Ciuraru

Reputation: 3477

Swift 3, 4, 5:

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

Upvotes: 8

Fogmeister
Fogmeister

Reputation: 77631

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

Upvotes: 14

Related Questions