简体   繁体   中英

How to get the day of week for a given date when the week begins on a Monday?

The Calendar API is confusing me. What I'm trying to do seems simple, but doesn't really appear to work for me.

I want to set the first day of the week to be Monday, rather than the default Sunday (I know it differs by Locale, but I want to enforce always Monday). On top of that, for a given date, I want to retrieve the day of the week it represents (eg, 1 for Monday, 7 for Sunday).

Is there any way to do this with the default Calendar API? I've tried something like:

Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTime(<some Date object that's a monday>);
System.out.println(cal.get(Calendar.DAY_OF_WEEK));

It gives me a 2, instead of a 1. I suspect it's because it's giving me the value of Calendar.MONDAY , but I'm not entirely sure. Based on that suspicion, the following does work:

Calendar cal = Calendar.getInstance();
cal.setTime(<some Date object that's a monday>);
System.out.println(
    (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) ? 
        7 : cal.get(Calendar.DAY_OF_WEEK) - 1);

... but I'd rather not have that if-statement. Is there a way to do what I want with the straight-up Calendar API?

Looking at the Calendar source it would appear that setFirstDayOfWeek really only impacts the WEEK_OF_MONTH and WEEK_OF_YEAR calculations. Regardless of what day your week starts on, MONDAY is still MONDAY, and in Calendar MONDAY has a value of 2.

Blockquote

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. The system's default can be overridden by a JVM parameter:

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)

Don't forget that this could change other behavio(u)r too.

Blockquote

Detail can be found at following link

How to specify firstDayOfWeek for java.util.Calendar using a JVM argument

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