如何解决无法根据当前语言环境获取日期
我在 tableview 中填充月份和日期。我有支持法语和英语的应用程序。但是当我将语言环境更改为法语时,我无法获得法语月份。只有在我再次启动应用程序时才会反映出来,而不是在我更改应用程序内的语言后立即反映出来。
这是我在 cellForRowAtIndexPath
...
let dic = myArray[indexPath.row] as! NSMutableDictionary
var utcTime = "\(dic["Due_Date"]!)"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss”
let currentLanguage = …. (Correctly gives ‘en’ OR ‘fr')
self.dateFormatter.locale = Locale.init(identifier: currentLanguage)
self.dateFormatter.timeZone = TimeZone(abbreviation: "UTC”)
if let date = dateFormatter.date(from:utcTime) {
let monthInt = Calendar.current.component(.month,from: date)
dayInt = Calendar.current.component(.day,from: date)
let yearInt = Calendar.current.component(.year,from: date)
let monthStr = Calendar.current.monthSymbols[monthInt-1]
print(monthStr,dayInt). //If the current language is ‘fr’ the month is printed here in English. It changes back to French only after I launch the app again
}
编辑:这就是我在应用程序中更改语言的方式..
有一个这样的类...
let APPLE_LANGUAGE_KEY = "AppleLanguages"
class TheLanguage {
class func currentAppleLanguage() -> String{
let userdef = UserDefaults.standard
let langArray = userdef.object(forKey: APPLE_LANGUAGE_KEY) as! NSArray
let current = langArray.firstObject as! String
return current
}
class func setAppleLAnguageTo(lang: String) {
let userdef = UserDefaults.standard
userdef.set([lang,currentAppleLanguage()],forKey: APPLE_LANGUAGE_KEY)
userdef.synchronize()
}
}
我得到了当前的语言......
let currentLanguage = TheLanguage.currentAppleLanguage()
解决方法
来自文档:
月符号: 此日历中的月份列表,已本地化为日历的语言环境。
所以我猜您需要将日历的区域设置更改为用户选择的区域设置。
编辑:
但是,如果您只需要给定日期的月份名称(不知道您的示例中的 DueDate 是什么类型),您可以使用以下代码:
let dueDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
dateFormatter.locale = Locale(identifier: "fr")
let month = dateFormatter.string(from: dueDate)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。