Here is the real calendar now:
March 2015
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
And I get DAY_OF_WEEK
of 2015/3/24
like this:
public class TestCalendar {
public static void main(String[] argvs){
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(2015,Calendar.MARCH,24);
System.out.println(cal.get(Calendar.DAY_OF_WEEK));
}
}
Since I have cal.setFirstDayOfWeek
to MONDAY
the result I expecting is 2
, but Whatever day I set to the first day of week
(have tried SUNDAY and others) .It kept show me the same result which is 3
. So It seemed that firstDayOfWeek
won't affect the result.
Have I do something wrong?
EDIT
I just figured and thanks to answers below, that this setFirstDayOfWeek
will not affect the result of get(Calendar.DAY_OF_WEEK)
nor get(Calendar.WEEK_OF_YEAR)
Then what is this method setFirstDayOfWeek()
designed for?
I mean How can I told the program that I want 2015/3/29
be the last day of the 12th week instead of treating it as the first day of the 13th week?
LocalDate.of( 2015 , Month.MARCH , 24 ) // `LocalDate` object for 2015-03-24.
.getDayOfWeek() // DayOfWeek.TUESDAY constant object
.getValue() // 2
Calendar
is a ugly mess, as are its sibling classes. Fortunately these old date-time classes are now legacy, supplanted by the java.time classes.
If you want Monday as the first day of the week, Sunday the last, numbered 1-7, then use the ISO 8601 calendar used by default in the java.time classes.
DayOfWeek
The DayOfWeek
enum hold predefined objects for each of those ISO days of the week. You can interrogate for its number if need be, though generally better to pass around objects of this enum rather than mere integers.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2015 , Month.MARCH , 24 );
DayOfWeek dow = ld.getDayOfWeek();
int value = dow.getValue(); // 1-7 for Monday-Sunday. But often better to use the `DayOfWeek` object rather than a mere integer number.
For working with other definitions of a week where Monday is not day number one, see the WeekFields
class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With