在 Java 中,如何使用系统的默认语言环境(语言)获取星期几(Sun、Mon、...、Sat)的字符串
最简单的方法:
String[] namesOfDays = new String[7] {
"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"
};
此方法不使用语言环境.因此,如果系统语言不是英文,这种方法就不能正常工作.
This method does not use Locale. Therefore, if the system's language is not English, this method does not work properly.
使用 Joda 时间,我们可以这样做:
Using Joda time, we can do like this:
String[] namesOfDays = new String[7];
LocalDate now = new LocalDate();
for (int i=0; i<7; i++) {
/* DateTimeConstants.MONDAY = 1, TUESDAY = 2, ..., SUNDAY = 7 */
namesOfDays[i] = now.withDayOfWeek((DateTimeConstants.SUNDAY + i - 1) % 7 + 1)
.dayOfWeek().getAsShortText();
}
但是,此方法使用今天的日期和日历计算,这对于最终目的是无用的.另外,它有点复杂.
However, this method uses today's date and calendar calculations, which are useless for the final purpose. Also, it is a little complicated.
有没有一种简单的方法来获取像 "Sun"
, "Mon"
, ..., "Sat"
这样的字符串和系统的默认语言环境?
Is there an easy way to get Strings like "Sun"
, "Mon"
, ..., "Sat"
with system's default locale?
推荐答案
如果我没有误会你
calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US);
是您正在寻找的.这里 你可以找到文档,
is what you are looking for. Here you can find the documentation,
或者您也可以使用 getShortWeekdays()
String[] namesOfDays = DateFormatSymbols.getInstance().getShortWeekdays()
相关文章