Question

I need to set some days in method set. I try to use:

c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);

but with this way set only Wednesday.

Thank you and sorry for my english :)

Was it helpful?

Solution

The Calendar does not function as you expect it to. From the JavaDoc:

The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

Notice that the documentation states a specific instant in time. This implies the Calendar can only be based off of one point in time from epoch.

When you use the set method you are adjusting the specific instant in time through each call. So first it gets set to Monday then Wednesday.

You could use a List<Calendar> to store multiple Calendar instances set to your desired days.

public class CalendarTest {
    public static void main(String[] args) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal2.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);

        List<Calendar> calendars = Arrays.asList(cal1, cal2);
    }
} 

OTHER TIPS

public static String getDay(String day,String month,String year){

    int mm = Integer.parseInt(month);
    int dd = Integer.parseInt(day);
    int yy = Integer.parseInt(year);
    LocalDate dt = LocalDate.of(yy, mm, dd);
    return dt.getDayOfWeek().toString().toUpperCase();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top