java.time
The LocalDate
class represents a date-only value without time-of-day and without time zone.
Specify your desired date as an anchor date, a date from which we count weeks. You want ordinal week numbers, so add one to avoid a week numbered zero.
The ChronoUnit
enum offers the between
method to calculate elapsed time.
LocalDate anchor = LocalDate.of( 2015 , Month.FEBRUARY , 2 );
LocalDate feb5 = LocalDate.of( 2015 , Month.FEBRUARY , 5 );
LocalDate feb8 = LocalDate.of( 2015 , Month.FEBRUARY , 8 );
LocalDate feb9 = LocalDate.of( 2015 , Month.FEBRUARY , 9 );
System.out.println( feb5 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb5 ) + 1 ) );
System.out.println( feb8 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb8 ) + 1 ) );
System.out.println( feb9 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb9 ) + 1 ) );
See this code run live at IdeOne.com.
2015-02-05 is in week # 1
2015-02-08 is in week # 1
2015-02-09 is in week # 2
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?
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.