tl;dr
LocalDate.of( 2012 , Month.AUGUST , 7 )
.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR )
32
Locale
Not sure of the direct answer to your Question, but likely to be differing Locale
values in play. In Calendar
the definition of a week varies by the locale.
But this is moot. You should be using the java.time classes that replaced Calendar
class.
java.time
Calendar
is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes. For earlier Android, see the last bullets below.
You must define what you mean by week number. There are different ways to define a week and week number.
By default, the java.time classes use the standard ISO 8601 definition: Week # 1 has the first Thursday of the calendar year, and starts on Monday (as you asked for). So years have either 52 or 53 weeks. The first and last few days of the calendar year may land in the prior/following week-based year.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2012 , Month.AUGUST , 7 ) ;
Interrogate for the standard week number. You can ask for either of these TemporalField
objects: IsoFields.WEEK_BASED_YEAR
& IsoFields.WEEK_OF_WEEK_BASED_YEAR
int weekOfWeekBasedYear = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
int yearOfWeekBasedYear = ld.get( IsoFields.WEEK_BASED_YEAR ) ;
Dump to console using standard ISO 8601 format of YYYY-Www-D
.
String isoOutput = yearOfWeekBasedYear + "-W" + String.format("%02d", weekOfWeekBasedYear) + "-" + dayOfWeekNumber ;
System.out.println( ld + " is ISO 8601 week: " + isoOutput ) ;
See this code run live at IdeOne.com.
2012-08-07 is ISO 8601 week: 2012-W32-2
By the way, if Android is ever able to run the ThreeTen-Extra library, you’ll find its YearWeek
class useful.
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?