tl;dr
myZonedDateTime.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR )
…and…
myZonedDateTime.get( IsoFields.WEEK_BASED_YEAR )
Avoid legacy date-time classes
As the correct Answer by haraldK explains, the Calendar
class’s definition of week varies by locale. While well-intentioned, this is confusing.
You should be avoiding Calendar
and related classes such as Date
. They are now supplanted by the java.time classes.
ISO 8601 week
As for ISO 8601 week, be clear that means:
- The first day is Monday, running through Sunday.
- Week number one of a week-based year contains the first Thursday of the calendar year.
- A week-based year has either 52 or 53 weeks.
- The first/last few days of a calendar year may appear in the previous/next week-based year.
java.time
The java.time classes include limited support for ISO 8601 standard weeks. Call the get
method on various classes such as LocalDate
and ZonedDateTime
. Pass the TemporalField
implementations found as constants in the IsoFields
class.
int week = myZonedDateTime.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
int weekBasedYear = myZonedDateTime.get( IsoFields.WEEK_BASED_YEAR ) ;
ThreeTen-Extra
Even better, add the ThreeTen-Extra library to your project to use YearWeek
class.
org.threeten.extra.YearWeek yw = YearWeek.from( myZonedDateTime ) ;
Beware of calendaring software settings
Never assume the definition of a week number. Be sure the source of such a number has the same definition of week as you, such as ISO 8601 definition.
For example, the Calendar app supplied by Apple with macOS defaults to a "Gregorian" calendar definition of week. As for what that means, I do not know as I could not find any documentation about their intent/definition. For ISO 8601 weeks, you must change a setting away from default.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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.