swiftlocalizationnslocalizedstringdateformatter

How do I localize a string that contains a date and the location of the text differs depending on the language?


I'm localizing my app for Hungarian users and having trouble figuring out how to handle a string with a date in it.

In English, I have a text string that should say "4 reps @ 120 kg on 8/19/23". I'm having trouble with the "on 8/19/23" part of that because in Hungarian the "on" comes after the date like this "19. 08. 23.-én". Here's my code for localizing "on 8/19/23"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.setLocalizedDateFormatFromTemplate("MMddyy")
let formattedDate = dateFormatter.string(from: viewData.liftDate)

let onDateText = NSLocalizedString("onDateText", 
                                    tableName: "Main", 
                                    value: formattedDate, <-- a string
                                    comment: "")

liftDate.text = onDateText

And in my localizable.strings file I have this:

"onDateText" = "%@-én";

And what's appearing in my app is "4 ismétlésszám @ 120.0 kg %@-én"

I need help understanding how to get the date included in the localized string that's returned.

Note: The screen this appears on is a UIViewController, not a SwiftUI view.

I've read lots of posts here on SO and have tried to figure it out using the commonly recommended String Programming Guide, but I can't figure it out.

Thanks for helping.


Solution

  • You need to use the result of NSLocalizedString as a string format. The value you pass in is the default string format.

    Your update code would look something like this:

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale.current
    dateFormatter.setLocalizedDateFormatFromTemplate("MMddyy")
    let formattedDate = dateFormatter.string(from: viewData.liftDate)
    
    let onDateFormat = NSLocalizedString("onDateText",
                                        tableName: "Main",
                                        value: "on %@",
                                        comment: "")
    
    liftDate.text = String(format: onDateFormat, formattedDate)
    

    Note the change in the value parameter for NSLocalizedString. Also note the use of String(format:) to create the final string.

    By having the base format string in NSLocalizedString, you can use the standard localization tools to generate the base Localizable.strings file from your code.

    At runtime, the actual value returned by NSLocalizedString will be the actual localized value based on the user's locale.