Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force localization of the allowedUnits in DateComponentsFormatter

I have an app with only one language. I would like to force the language to be this when displaying a time interval since a date. E.g. "9 mths ago" Just in a specific language not english. Is there a way to do this using DateComponentsFormatter which otherwise does exactly what I want to do with the units.

    func format(duration: TimeInterval) -> String {
        UserDefaults.standard.set(["da"], forKey: "AppleLanguages")
        UserDefaults.standard.synchronize()
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
        formatter.unitsStyle = .short
        formatter.includesApproximationPhrase = true
        formatter.maximumUnitCount = 1

        return formatter.string(from: -duration)!
    }

    format(duration: self.createdDate.timeIntervalSinceNow)

This returns e.g. "1 yr" when language is en. I would like to have it in a specific language ("yr" -> "år") this should be similarly done for the other allowed units.

It works when the phone is set to the language of the app.

I tried to set the language before creating the DateComponentsFormatter but it still returned in the language the phone is set to.

EDIT inserted working code below

Working code after modification from answer:

    func format(duration: TimeInterval) -> String {
        var calendar = Calendar.current
        calendar.locale = Locale(identifier: "da")
        let formatter = DateComponentsFormatter()
        formatter.calendar = calendar
        formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
        formatter.unitsStyle = .short
        formatter.includesApproximationPhrase = true
        formatter.maximumUnitCount = 1

        return formatter.string(from: -duration)!
    }

    format(duration: self.createdDate.timeIntervalSinceNow)
like image 545
user12345625 Avatar asked Dec 22 '16 12:12

user12345625


1 Answers

It's default iOS behavior. If you change your locale and language on phone, you'll notice that is possible to have 2 languages in Calendar application. Sometimes it's possible to change locale, but includesApproximationPhrase in your example will not be translated:

var calendar = Calendar.current
calendar.locale = Locale(identifier: "da")
let formatter = DateComponentsFormatter()
formatter.calendar = calendar
like image 83
Timur Bernikovich Avatar answered Oct 31 '22 09:10

Timur Bernikovich