1

I would like to display the time of the current date in a UILabel in the current locale. Assuming the current time would be 15:30 (24 hours display) / 3:30 PM (12 hours display). Now, if the current locale of the user is 12 hours display, the label should only show "3:30", and the "PM" should display in a second label. I intended to use

someDateTime = Date()
let df = DateFormatter()
df.locale = Locale.autoupdatingCurrent
df.timeStyle = .short
timeLabel.text =  df.string(from: someDateTime) // how without AM/PM ?
ampmLabel.text = "???" // how to show only in 12 hours regions?

But in 12 hours regions it comes always with the AM/PM attached to it. How could I easily distinguish these cases?

Pauli
  • 343
  • 1
  • 4
  • 17

1 Answers1

1

One solution would be to generate the time string from your date formatter and then see if the resulting string contains either the amSymbol or pmSymbol of the date formatter. If it does, save off that symbol and remove it from the date string. Then you will have the two strings you need.

let timeDF = DateFormatter()
timeDF.locale = ... // whatever you need of other than the user's current
timeDF.dateStyle = .none
timeDF.timeStyle = .short
var timeStr = timeDF.string(from: Date())
var ampmStr = ""
if let rng = timeStr.range(of: timeDF.amSymbol) {
    ampmStr = timeDF.amSymbol
    timeStr.removeSubrange(rng)
} else if let rng = timeStr.range(of: timeDF.pmSymbol) {
    ampmStr = timeDF.pmSymbol
    timeStr.removeSubrange(rng)
}

timeLabel.text = timeStr.trimmingCharacters(in: .whitespaces)
ampmLabel.text = ampmStr
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • thanks, that could work if I set the locale to the current user's one (cause I need to display the time with the current user's locale). Could you maybe add this, so I can mark complete? It is a bit string analysis though - I thought there would be a cleaner way by finding out if the current user's locale would use AM/PM (12hours) or 24 hours system... – Pauli Oct 19 '18 at 05:21
  • 1
    If you want the user's current locale then there is no need to set the date formatter's locale because it defaults to the user's current locale. – rmaddy Oct 19 '18 at 06:15
  • 1
    If you simply want to know if the user's locale uses AM/PM you can look at the value of `timeDF.format` after setting the `timeStyle`. If the format contains `"a"` then the locale uses AM/PM. But also note this is also affected by the user's settings such as the 12/24 hour setting. This can override the locale's default setting. – rmaddy Oct 19 '18 at 06:18