Sye*_*yed 4 java time android date
如何在不更改设备语言的情况下更改android中的日期/时间语言.
以下是我目前的代码.下面的代码根据设备语言而变化.但我想在不更改设备语言设置的情况下进行更改
public static String formatTime(Date time)
{
String timeFormat = UserSettingManager.getUserSetting(UserSettingManager.PREF_TIME_FORMAT);
if(StringUtils.isEmptyOrWhitespace(timeFormat))
{
timeFormat = DEFAULT_TIME_FORMAT;
}
SimpleDateFormat formatter;
try
{
formatter = new SimpleDateFormat(timeFormat);
}
catch(Exception e)
{
formatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT);
}
return formatter.format(time);
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
public static String formatTime(Date time, Locale locale){
String timeFormat = UserSettingManager
.getUserSetting(UserSettingManager.PREF_TIME_FORMAT);
if(StringUtils.isEmptyOrWhitespace(timeFormat)){
timeFormat = DEFAULT_TIME_FORMAT;
}
SimpleDateFormat formatter;
try {
formatter = new SimpleDateFormat(timeFormat, locale);
} catch(Exception e) {
formatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT, locale);
}
return formatter.format(time);
}
Run Code Online (Sandbox Code Playgroud)
然后喜欢
Log.e("CHINESE DATE", formatTime(new Date(), Locale.CHINESE));
Run Code Online (Sandbox Code Playgroud)
如果在默认列表中未找到语言环境,则可以使用其构造函数实例化一个语言环境:
Locale spanish = new Locale("es", "ES");
Run Code Online (Sandbox Code Playgroud)
所以它变成了
Log.e("SPANISH DATE", formatTime(new Date(), new Locale("es", "ES"));
Run Code Online (Sandbox Code Playgroud)