How to make java calendar to start weekday from Mo

2019-06-26 07:49发布

问题:

I have written code, which uses Java calendar and shows the DAY_OF_WEEK from timestamp. But the default calendar starts from Sunday (1). I want it start from Monday eg. It should return 1 for Monday. Here's my code :

Calender c = Calender.getInstance(TimeZone.getInstance("Australia/Sydney"));
c.setTimeInMillis(1413831601032L);
c.setFirstDayOfWeek(Calender.Monday);
System.out.println(c.get(c.DAY_OF_WEEK));

setFirstDayOfWeek() doesn't help in this case.

The output should be 2 for Tueday, but its showing me 3. Any help will be appreciated.

回答1:

The first day of the week is derived from the current locale. If you don't set the locale of the calendar (Calendar.getInstance(Locale), or new GregorianCalendar(Locale)), it will use the system's default.

public static void main(String[] args) {
    Calendar c = new GregorianCalendar();
    System.out.println(Locale.getDefault() + ": " + c.getFirstDayOfWeek());
}

This should show a different output with different JVM parameters for language/country:

-Duser.language=en -Duser.country=US -> en_US: 1 (Sunday)
-Duser.language=en -Duser.country=GB -> en_GB: 2 (Monday)

Also, You can use the method setFirstDayOfWeek() to set the first day of the week. The method can only affect the return values of WEEK_OF_MONTH or WEEK_OF_YEAR. For DAY_OF_WEEK, it does nothing.

Refer here for more

Also if you see the Calendar.java, you will see that values for days is constant, as below. So that's why it will return 1 for MONDAY, no matter what the first day of the week is set to.

public final static int SUNDAY = 1;

public final static int MONDAY = 2; ....

public final static int SATURDAY = 7;

You can do something as below and manipulate the data, according to the first day you are setting.

[c.get(Calendar.DAY_OF_WEEK) - 1]);


回答2:

Try to avoid to use the raw values returned by get. In your code you should make a check always against the constants defined in the Calendar class. This has the big advantage it's more readable.

Consider following snippets

Here it's hard to find for which day of week you want to do which action

switch (c.get(Calendar.DAY_OF_WEEK)) {
    case 2: 
        // do something
        ; break;
    case 3: 
        // do something
        break;

}

This example is more self-explaining

switch (c.get(Calendar.DAY_OF_WEEK)) {
    case Calendar.MONDAY: 
        // do something
        ; break;
    case Calendar.TUESDAY: 
        // do something
        break;

}


标签: java calendar