语言特定日期在Swift中的本地化

时间:2017-09-20 09:00:07

标签: ios swift date localization nslocalizedstring

我正在使用这段代码将日期本地化为Swift中的字符串:

if elapsedTime > 3600 { 
        let hourString = NSLocalizedString("hour ago", tableName: "v1.0.0", bundle: Bundle.main, value: "hour ago", comment: "")
        let hoursString = NSLocalizedString("hours ago", tableName: "v1.0.0", bundle: Bundle.main, value: "hours ago", comment: "")
        let hours = Int(elapsedTime/3600)
        return "\(hours) " + (hours > 1 ? hoursString : hourString)
}

其中elapsedTime是以秒为单位的值。 英语本地化的结果是

例如

6 hours ago。我需要对其进行修改以添加特定于语言的本地化,例如在法语中,它不应采用[N] hours agoil ya [N] heurs的格式。有没有办法自动化它,避免为它使用的不同语言添加特定的前缀? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

基于@Larme评论工作版本如下:

if elapsedTime > 3600 { 
        let hours = Int(elapsedTime / 3600)
        let hourString = NSLocalizedString("hour ago", tableName: "v1.0.0", bundle: Bundle.main, value: "hour ago", comment: "")
        let hoursString = String(format: NSLocalizedString("hours ago", tableName: "v1.0.0", bundle: Bundle.main, value: "\(hours) hours ago", comment: ""),
                           arguments: [hours])
        return (hours > 1 ? hoursString : hourString)
    }

对v1.0.0.strings(法语)所做的更改是

"hours ago" = "il y a %d heures";