问题
I need to show date and time in this format, Date: 9th Dec, Time: 19:20
Although my following code is working fine in English, have no idea this is correct way in other languages which my application is supporting like Chinese, Thai, etc. Any idea would be appreciated? Thanks
This is my code:
private String getFormattedTime(Calendar calendar)
{
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
StringBuilder sBuilder = new StringBuilder(4);
sBuilder.append(hour);
sBuilder.append(":");
// We want to display the hour like this: 12:09,
// but by not using following code it becomes 12:9
if (minute < 10)
{
sBuilder.append("0");
}
sBuilder.append(minute);
return sBuilder.toString();
}
private String getDateSuffix( int day)
{
if (day < 1 || day > 31)
{
throw new IllegalArgumentException("Illegal day of month");
}
switch (day)
{
case 1:
case 21:
case 31:
return ("st");
case 2:
case 22:
return ("nd");
case 3:
case 23:
return ("rd");
default:
return ("th");
}
}
回答1:
I would recommend that you use Joda Time.
Here is an example from their Quick Start Guide.
DateTime dt = new DateTime();
String monthName = dt.monthOfYear().getAsText();
String frenchShortName = dt.monthOfYear().getAsShortText(Locale.FRENCH);
While "Dec" could mean December or décembre, Joda will use the correct one, depending on Locale
.
Since Locale.CHINESE
and Locale.THAI
are available, it will do the translation for you.
If you use Java 8, Joda comes with the package.
You will save yourself a mountain of work if you use this package.
回答2:
I did some research based on what @MadProgrammer said and this is my code for those how have same problem. DateFormat and SimpleDateFormat Examples.
private String getFormattedDate(Calendar calendar)
{
Date date = calendar.getTime(); // out: Dec 9, 2014
// String str = DateFormat.getDateInstance().format(date);
// Log.d(TAG, str);
String str = new SimpleDateFormat("MMM d").format(date);
// Log.d(TAG, str);
return str;
}
private String getFormattedTime(Calendar calendar)
{
Date date = calendar.getTime();
String str = DateFormat.getTimeInstance(DateFormat.SHORT).format(date);
// Log.d(TAG, str);
return str;
}
来源:https://stackoverflow.com/questions/27370387/how-to-format-date-time-in-language-independent-way