java.time
The Joda-Time project is now in maintenance-mode. Its creator Stephen Colebourne went on to found the JSR 310 project that put java.time classes into Java 8 and later.
ThreeTen-Extra library
The same Stephen Colebourne also created the ThreeTen-Extra project. This project produces a library that includes the YearWeek
class for your purposes.
ISO 8601 week
Well it suits your purposes if you define “week” according to the ISO 8601 standard definition:
- Week # 1 contains the first Thursday of the calendar year.
- Week runs Monday-Sunday.
- A week-based year is composed of exactly 52 or 53 complete 7-day weeks.
So the first & last weeks may contain some days from the previous & following calendar years.
YearWeek
class
Using the YearWeek
class is quite simple.
YearWeek currentWeek = YearWeek.now() ; // Or now( ZoneId.of( "America/Edmonton" ) )
Get the week for a date.
YearWeek yw = YearWeek.of( LocalDate.of( 2025 , Month.JANUARY , 23 ) ) ;
Regarding your input string:
Example: 2014-06_03 where 03 is the third week of this month
… this has no clear meaning. You neglected to explain your definition of week.
We could get the third week, per ISO 8601 standard, that occurs in the month of June.
String input = "2014-06_03";
String[] parts = input.split ( "_" );
YearMonth yearMonth = YearMonth.parse ( parts[ 0 ] );
int week = Integer.parseInt ( parts[ 1 ] );
YearWeek firstWeekInMonth = YearWeek.from ( yearMonth.atDay ( 1 ) );
YearWeek nthWeekInMonth = firstWeekInMonth.plusWeeks ( week - 1 );
Dump to console.
System.out.println ( "yearMonth.toString() = " + yearMonth );
System.out.println ( "firstWeekInMonth.toString() = " + firstWeekInMonth );
System.out.println ( "nthWeekInMonth.toString() = " + nthWeekInMonth );
System.out.println ( nthWeekInMonth.atDay ( DayOfWeek.MONDAY ) + "/" + nthWeekInMonth.atDay ( DayOfWeek.SUNDAY ) + " (inclusive)" );
yearMonth.toString() = 2014-06
firstWeekInMonth.toString() = 2014-W22
nthWeekInMonth.toString() = 2014-W24
2014-06-09/2014-06-15