简体   繁体   中英

Java Calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY), will it roll backwards, forwards or unknown?

Suppose the following code is executed on the 22nd of August 2009 (a Saturday)

   Calendar c = Calendar.getInstance();
   c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

c.get(Calendar.DAY_OF_MONTH) will return 23. I'm interested in the conditions is would return 14 (last Sunday, rather than the next Sunday).

Are there any rules associated with the direction Calendar will roll the DAY_OF_MONTH/YEAR when DAY_OF_WEEK is set? If so what are they?

It should always keep the same WEEK_OF_MONTH ( http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#WEEK_OF_MONTH ). From the documentation:

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get() may be different. For example, a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.

the following formula returns "current" day in a week in range of [0;6]

(d + numberOfDaysInAWeek - firstDayOfWeek) % numberOfDaysInAWeek

or add 1 if you would like range [1;7]

(d + numberOfDaysInAWeek - firstDayOfWeek) % numberOfDaysInAWeek + 1

d is what Calendar.get(Calendar.DAY_OF_WEEK) returns

to get first day of a week, subtract formula's result from current date. The following code does it:

final int currentDayOfWeek = (calendar.get(Calendar.DAY_OF_WEEK) + 7 - cal.getFirstDayOfWeek()) % 7;
cal.add(Calendar.DAY_OF_YEAR, -currentDayOfWeek);

It depends, actually. Consider the following Java code. It is actually quite simple and I expect it to print the monday preceding 2011-09-18, that is 2011-09-12:

Calendar calendar = Calendar.getInstance(Locale.GERMANY);
System.out.printf("First day of week: %d%n%n", calendar.getFirstDayOfWeek());

calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n%n", calendar);

calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF (week %d)%n",
        calendar, calendar.get(Calendar.WEEK_OF_YEAR));
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF (week %d)%n", calendar,
        calendar.get(Calendar.WEEK_OF_YEAR));

But in fact the result is a bit different:

First day of week: 2

Starting day: 2011-09-18
Last monday: 2011-09-19

Starting day: 2011-09-18 (week 37)
Last monday: 2011-09-12 (week 37)

In other words, the result depends on whether my calendar knows that I might be interested in the week. The result actually changes if I query WEEK_OF_YEAR !

Using java.time

The modern approach is with the java.time classes that supplant the troublesome old legacy date-time classes.

The java.time classes are much easier to work with. In particular, they remove the ambiguity raised in the Question. You can explicitly ask either for the earlier Sunday or for the later Sunday.

The LocalDate class represents a date-only value without time-of-day and without time zone.

The Month enum provides a dozen pre-defined objects, one for each month of the year. These enum objects are safer to use, but you can instead use a plain number for the month. Unlike the legacy classes, these months have sane numbering, 1-12 for January-December.

LocalDate localDate = LocalDate.of( 2009 , Month.AUGUST, 22 );

The TemporalAdjuster interface provides for manipulation of date-time values. The TemporalAdjusters class (note the plural s ) provides several handy implementations.

The previous & next adjusters exclude the date itself from consideration. The previousOrSame & nextOrSame methods return the date in question if it is indeed the desired day-of-week.

The DayOfWeek enum provides seven pre-defined objects, one for each day of the week.

LocalDate previousSunday = localDate.with( TemporalAdjusters.previous ( DayOfWeek.SUNDAY ));
LocalDate previousOrSameSunday = localDate.with( TemporalAdjusters.previousOrSame ( DayOfWeek.SUNDAY ));

LocalDate nextSunday = localDate.with( TemporalAdjusters.next ( DayOfWeek.SUNDAY ));
LocalDate nextOrSameSunday = localDate.with( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ));

Dump to console.

System.out.println ("localDate: " + localDate + " ( " + localDate.getDayOfWeek ().getDisplayName ( TextStyle.FULL, Locale.US )  + " )");
System.out.println ("previousSunday: " + previousSunday );
System.out.println ("nextSunday: " + nextSunday );

localDate: 2009-08-22 ( Saturday )

previousSunday: 2009-08-16

nextSunday: 2009-08-23


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

From the Javadoc :

If there is any conflict in calendar field values, Calendar gives priorities to calendar fields that have been set more recently. The following are the default combinations of the calendar fields. The most recent combination, as determined by the most recently set single field, will be used.

For the date fields:

 YEAR + MONTH + DAY_OF_MONTH
 YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
 YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
 YEAR + DAY_OF_YEAR
 YEAR + DAY_OF_WEEK + WEEK_OF_YEAR

I interpret this to mean that given that you're setting day of week, it will end up being combined with week of month or week of year in order to produce the actual date and time.

You should also check what is the first day in a week. I also thought it is always Sunday, but this depend on local settings, and in my case Monday is the first day in week. Setting Sunday as first day of the week fixed my problem.

Depends on the first day of the week:

 /**
 * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
 * <code>MONDAY</code> in France.
 *
 * @return the first day of the week.
 * @see #setFirstDayOfWeek(int)
 * @see #getMinimalDaysInFirstWeek()
 */
public int getFirstDayOfWeek()
{
    return firstDayOfWeek;
}

You can use like this method.

public Integer whichDayOfWeek(Calendar calendar) {
            if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                return 1;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
                return 2;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
                return 3;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
                return 4;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
                return 5;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
                return 6;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                return 7;
            } else {
                return null;
            }
        }

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