3 回答

TA貢獻1818條經驗 獲得超11個贊
嘗試這個:
我已經制作了一個擴展功能,可以使用應用程序的默認語言環境或僅使用英語來格式化日期。
注意:此函數將始終以英語返回格式化日期,無論您的設備語言是什么或您的應用程序語言是什么。
如果您想根據您的應用程序語言進行約會,只需將您應用程序選擇的語言區域設置傳遞給此方法即可。
在展示之前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"
)
)

TA貢獻1790條經驗 獲得超9個贊
由于沒有有用的答案,我將針對此問題發布我的解決方案。
所以我決定為每種支持的語言創建 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)
}

TA貢獻1824條經驗 獲得超8個贊
獲取系統語言
Resources.getSystem().getConfiguration().locale.getLanguage();
獲取應用程序語言
String appLang = Locale.getDefault().getLanguage();
添加回答
舉報