Java java.util.Calendar 中语言环境设置的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15186208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is purpose of locale setting in Java java.util.Calendar?
提问by Artegon
I am obtaining information (such as number of a day in week, month, year etc) about particular date in Java via java.util.Calendar. Is there some reason to set locale for calendar object in my situation? I am asking beacuse:
我正在通过 java.util.Calendar 获取有关 Java 中特定日期的信息(例如周、月、年等中的一天数)。在我的情况下,是否有理由为日历对象设置语言环境?我问是因为:
System.out.println(cal.get(Calendar.DAY_OF_WEEK));
returns for today (Sunday) always number 1 but in our locale (cs_CZ) it should be 7.
今天(周日)的返回值始终为 1,但在我们的语言环境 (cs_CZ) 中,它应该是 7。
Locale locale = new Locale("cs", "CZ");
TimeZone tz = TimeZone.getTimeZone("Europe/Prague");
Calendar cal = GregorianCalendar.getInstance(tz, locale);
cal.setTime(new Date());
// returns => 1 (but I expected 7)
System.out.println(cal.get(Calendar.DAY_OF_WEEK));
// returns => 3 - it's OK
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
EDIT:I can hadle with 1 for Sunday, but I must be sure this is unchanging behaviour regardless to used Locale or TimeZone.
编辑:我可以在周日使用 1,但我必须确保无论使用 Locale 还是 TimeZone,这都是不变的行为。
采纳答案by Artegon
回答by shuangwhywhy
Locale do will affect the first day of week. However, the day values are constants, SUNDAY
is always 1. You can check this link. The get()
method just returns the correct field value (If it returns 7 then it's wrong -- 7 is SATURDAY
, not the current day).
Locale do 会影响一周的第一天。但是,天值是常数,SUNDAY
始终为 1。您可以查看此链接。该get()
方法只返回正确的字段值(如果它返回 7 那么它是错误的——7 是SATURDAY
,而不是当天)。
But you can call getFirstDayOfWeek()
and it returns 2 (MONDAY
). I think this is what you need. You can take use of these two methods to reach your goal.
但是你可以调用getFirstDayOfWeek()
它,它返回 2 ( MONDAY
)。我认为这就是你所需要的。您可以使用这两种方法来达到您的目标。
System.out.println((cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() + 7) % 7 + 1);
The above statements returns 7.
上述语句返回 7。