Android Java calendar replacement with the following features
I need to start my calendar on Monday.
According to today’s date (August 7, 2012), the first day is Monday, the minimum number of days of the week is 1, java gives me the 33rd week of the year and android is 32, why?
So I need a calendar replacement with the following features.
The code I’m using:
Calendar cal = Calendar.getInstance(); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setMinimalDaysInFirstWeek(1); out("For date : "+df.format(cal.getTime())+" Week = "+cal.get(Calendar.WEEK_OF_YEAR));
Does it help?
LocalDate.of( 2012 , Month.AUGUST , 7 ) .get( IsoFields.WEEK_OF_WEEK_BASED_YEAR )
Not sure of the direct answer to your question, but most likely a different
Locale value is at work. In
Calendar, the definition of the week varies by region.
But this is moot. You should use the java.time class that replaces the
Calendar is part of the troublesome old datetime classes that are now left behind, replaced by the java.time class. For earlier Androids, see the last bullet below.
You must define what the week number means. There are different ways to define weeks and week numbers.
By default, the java.time class uses the standard ISO 8601 definition : Week 1 is the first Thursday of the calendar year, starting on Monday (as you requested). So the year has 52 or 53 weeks. The first and last days of the calendar year may fall on the pre/after year based on the week.
The LocalDate class represents a pure date value without time and time zone.
LocalDate ld = LocalDate.of( 2012 , Month.AUGUST , 7 ) ;
int weekOfWeekBasedYear = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ; int yearOfWeekBasedYear = ld.get( IsoFields.WEEK_BASED_YEAR ) ;
Use standard dumps to the console ISO 8601 format of
String isoOutput = yearOfWeekBasedYear + "-W" + String.format("%02d", weekOfWeekBasedYear) + "-" + dayOfWeekNumber ; System.out.println( ld + " is ISO 8601 week: " + isoOutput ) ;
Check out this code run live at IdeOne.com
2012-08-07 is ISO 8601 week: 2012-W32-2
Where do I get the java.time class?
- Java SE 8 , Java SE 9, then
- Part of a standard Java API with a bundle implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Many java.time features are backported to Java 6 and 7 in ThreeTen-Backport