Fyodor Volchyok
Fyodor Volchyok

Reputation: 5673

iOS localized string constants for time symbols ("MINUTE(S)", "HOUR(S)" etc.)

I am writing an app which need to show dates with corresponding time symbols like "hours", "minutes" etc. There are cool localized constants for months and weekdays names in NSDateFormatter like monthSymbols (January, February etc). However, I can't find anything like this for such symbols as "hour", "minute" itself. Does such constants exists or I should create and localize these symbols by myself?

UPD: My goal is a text for label under "30" - only localized "MIN" string without any numbers I should get rid of before placing text from date formatter in the label at the bottom. enter image description here

Upvotes: 5

Views: 2081

Answers (3)

Calin Drule
Calin Drule

Reputation: 2949

Not very pretty, but works:

var localizedMinutesShort: String {
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .short
    formatter.allowedUnits = [.minute]

    let date = Date()

    let dateComponents = Calendar.current.dateComponents([.minute], from: date)
    let dateString = formatter.string(from: dateComponents)
    
    return dateString?.filter { $0.isLetter } ?? "min"
}

Inspired by @Tom Harrington solution.

Upvotes: 0

rica2988
rica2988

Reputation: 156

If you need just the min string localized you can use a MeasurementFormatter()

let measurementFormatter: MeasurementFormatter = {
    let measurementFormatter = MeasurementFormatter()
    measurementFormatter.locale = Locale.current
    measurementFormatter.unitOptions = .providedUnit
    measurementFormatter.unitStyle = .short        
    return measurementFormatter
}()

label.text = measurementFormatter.string(from: UnitDuration.minutes)

Upvotes: 10

Tom Harrington
Tom Harrington

Reputation: 70946

Depending on the details of what you need, NSDateComponentsFormatter might be the solution. It includes NSDateComponentsFormatterUnitsStyleSpellOut, which renders strings in formats like “One hour, ten minutes”.

Update: After reading comments I'm still not sure what kind of formatting you really need. But hopefully this will be a useful example:

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Full
formatter.allowedUnits = [ NSCalendarUnit.Minute, NSCalendarUnit.Hour ]

let date = NSDate()

let dateComponents = NSCalendar.currentCalendar().components([.Minute, .Hour], fromDate: date)
let dateString = formatter.stringFromDateComponents(dateComponents)

At this point, dateString will be something like "15 hours, 11 minutes".

Upvotes: 10

Related Questions