3

Is there support in the java.time classes, or its extension ThreeTen-Extra, for a week dates, specifically a Year-Week-Day such as 2009-W53-7 which is Sunday 3 January 2010.

As for the year-week without the day-of-week:

But how to represent the day-of-week as well?

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154

1 Answers1

3

See the IsoFields class, which allows the week-based year and week of week-based year to be queried. There is also a dedicated formatter ISO_WEEK_DATE.

The DayOfWeek enum tells you the number of the day-of-week, 1-7 for Monday to Sunday. Call LocalDate::getDayOfWeek and then DayOfWeek::getValue.

LocalDate ld = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;

2016-12-07

int weekOfWeekBasedYear = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
int yearOfWeekBasedYear = ld.get( IsoFields.WEEK_BASED_YEAR ) ;
int dayOfWeek = ld.getDayOfWeek().getValue();

Use these parts to build strings in the standard ISO 8601 week date formats.

String yearWeek = yearOfWeekBasedYear + "-W" + String.format( "%02d", weekOfWeekBasedYear ) ; 

2016-W49

String yearWeekDay = yearWeek + "-" + dayOfWeek ;

2016-W49-3

Or, let the predefined DateTimeFormatter.ISO_WEEK_DATE do the work.

String ywd = ld.format( DateTimeFormatter.ISO_WEEK_DATE );

2016-W49-3

That same formatter can parse such standard strings.

String input = "2016-W49-3" ;
LocalDate ldParsed = LocalDate.parse( input , DateTimeFormatter.ISO_WEEK_DATE ) ;

2016-12-07

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
JodaStephen
  • 60,927
  • 15
  • 95
  • 117