RelativeDateTimeFormatter Context for Localised String

Viewed 243

I have a RelativeDateTimeFormatter that I'm using to sho strings like this: "Next lottery draw in 2 days" "Next lottery draw tomorrow"

This comes from the strings file with string format like this "Next lottery draw %@"

My problem is how do I localise this properly when the %@ is in a different place in the string. For example, in Japanese the %@ is somewhere in the middle of the string.

Here's my code for setting up the date formatter.

let exampleDate = Date().addingTimeInterval(-15000)

let formatter = RelativeDateTimeFormatter()
formatter.context = .dynamic

let relativeDate = formatter.localizedString(for: exampleDate, relativeTo: Date())

let myString = String(format: NSLocalizedString("string_key", comment: ""), relativeDate)

Formatters have a context you can pass to tell the formatter where the string's going to be used. https://developer.apple.com/documentation/foundation/formatter/context

And one of the cases is called dynamic which says that it's going to determine it at runtime. However, I can't see how that works or how I'm supposed to use the RelativeDateTimeFormatter with that.

0 Answers
Related