简体   繁体   中英

What is purpose of locale setting in Java java.util.Calendar?

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:

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.

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.

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).

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.

System.out.println((cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() + 7) % 7 + 1);

The above statements returns 7.

Finally I used Joda Time library:

DateTime dt = new DateTime(new Date());
int dayOfWeek = dt.getDayOfWeek();

and it returns 7 for today (Sunday).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM