我想使用 getRelativeTimeSpanString 来显示日期。但是我无法将 Locale 设置为此类以根据我的语言环境显示日期!我怎样才能自定义这个类?是否可以将语言环境作为参数添加到此类?
final CharSequence relativeTimeSpanString = DateUtils.getRelativeTimeSpanString(createdTime.getTime());
我还在我的应用程序中设置了语言环境:
Configuration configuration = new Configuration();
if (!TextUtils.isEmpty(lang)) {
configuration.locale = new Locale(lang);
} else {
configuration.locale = Locale.getDefault();
}
context.getResources().updateConfiguration(configuration,
context.getResources().getDisplayMetrics());
有没有办法解决这个问题?
最后我找到了解决这个问题的方法!
我使用了这种方法:
public static String getRelativeTimeSpanString(Context context, Date fromdate) {
long then;
then = fromdate.getTime();
Date date = new Date(then);
StringBuffer dateStr = new StringBuffer();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar now = Calendar.getInstance();
int days = daysBetween(calendar.getTime(), now.getTime());
int weeks= days/7;
int minutes = hoursBetween(calendar.getTime(), now.getTime());
int hours = minutes / 60;
if (days == 0) {
int second = minuteBetween(calendar.getTime(), now.getTime());
if (minutes > 60) {
if (hours >= 1 && hours <= 24) {
dateStr.append(String.format("%s %s %s",
hours,
context.getString(R.string.hour)
,context.getString(R.string.ago)));
}
}else {
if (second <= 10) {
dateStr.append(context.getString(R.string.now));
} else if (second > 10 && second <= 30) {
dateStr.append(context.getString(R.string.few_seconds_ago));
} else if (second > 30 && second <= 60) {
dateStr.append(String.format("%s %s %s",
second,
context.getString(R.string.seconds)
,context.getString(R.string.ago)));
} else if (second >= 60 && minutes <= 60) {
dateStr.append(String.format("%s %s %s",
minutes,
context.getString(R.string.minutes)
,context.getString(R.string.ago)));
}
}
} else
if (hours > 24 && days < 7) {
dateStr.append(String.format("%s %s %s",
days,
context.getString(R.string.days)
,context.getString(R.string.ago)));
}else if(weeks == 1){
dateStr.append(String.format("%s %s %s",
weeks,
context.getString(R.string.weeks)
,context.getString(R.string.ago)));
}
else {
/**
* make formatted createTime by languageTag("fa")
*
* @return
*/
return SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG,new Locale("fra"))
.format(date).toUpperCase();
}
return dateStr.toString();
}
public static int minuteBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / android.text.format.DateUtils.SECOND_IN_MILLIS);
}
public static int hoursBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / android.text.format.DateUtils.MINUTE_IN_MILLIS);
}
public static int daysBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / android.text.format.DateUtils.DAY_IN_MILLIS);
}
我将日期设置为该方法的参数:
return getRelativeTimeSpanString(context,this.createdTime);
这个按我想要的位置返回字符串!