[英]Detect application language instead of phone language
獲取系統語言
Resources.getSystem().getConfiguration().locale.getLanguage();
獲取應用語言
String appLang = Locale.getDefault().getLanguage();
嘗試這個:
我已經制作了一個擴展函數來使用應用程序的默認語言環境或僅使用英語來格式化日期。
注意:此功能將始終以英語返回格式化日期,無論您的設備語言是什么或您的應用語言是什么都無關緊要。
如果您希望按照應用語言約會,只需將應用的所選語言區域設置傳遞給此方法即可。
顯示之前DatePickerDialog
設置Locale
來en
這樣。
Locale.setDefault(Locale("en"))
startDatePickerDialog.show()
然后使用此方法格式化日期。
fun Context.getFormattedDate(
inputFormat: String = "dd/MM/yyyy",
outputFormat: String,
inputDate: String,
locale: Locale = Locale("en")
): String {
val inputFormat = inputFormat
var outputFormat = outputFormat
var parsed: Date? = null
var outputDate = ""
val dfInput = SimpleDateFormat(inputFormat, locale)
val dfOutput = SimpleDateFormat(outputFormat, locale)
try {
parsed = dfInput.parse(inputDate)
outputDate = dfOutput.format(parsed)
} catch (e: Exception) {
Log.e("formattedDateFromString", "Exception in formate Date From string(): " + e.message)
e.printStackTrace()
}
return outputDate
}
如何使用此功能
Log.e("Formated date", getFormattedDate(
inputFormat = "dd/MM/yyyy",
outputFormat = "dd-MMM-yyyy",
inputDate = "17/05/2019"
)
)
由於沒有有用的答案,我將發布我的解決方案來解決這個問題。
所以我決定使用里面的語言環境代碼為每種支持的語言創建xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="language_locale">en</string>
</resources>
用法示例:
fun Date.formatWithShortMonthAndDay(context: Context, date: Date): String {
val locale = context.resources.getString(R.string.language_locale)
return SimpleDateFormat(DATE_WITH_SHORT_MONTH_AND_DAY_PATTERN, Locale(locale)).format(date)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.