I've got week data in ISO 8601 format. E.g.:
weekA = '2012-W48'
weekB = '2013-W03'
Is there a class in Java that can represent those weeks and supports basic temporal operations? I tried LocalDate.parse("2012-W48",DateTimeFormatter.ISO_WEEK_DATE); but this throws an error because this is a week, not an actual date (i.e. the day in the week is missing). Similar to the LocalDate class, I'd like to be able to do some basic temporal operations such as:
weekA.isBefore(weekB)returnstrueifweekAis beforeweekBweeksBetween(weekA,weekB)returns the number of weeks between the two week dates, i.e.weekB-weekAin weeks.
Ideally I'd only use standard Java classes (Java >= 11).
Using standard library
The original solution (check below) was using an external library. The credit for this solution goes to user85421. The idea is to parse the given string into a
LocalDateby defaulting the day of the week to day-1.Output:
Online Demo
Using an external library (original solution)
You can use the ThreeTen-Extra library for your requirements.
You can use
YearWeek, and itsisBeforeandisAftermethods.You can use
java.time.temporal.ChronoUnit#betweento calculate the amount of time between twoYearWeekobjects. Alternatively, you can useYearWeek#untilto get the same result.Given below is the Maven dependency for it:
Demo:
Output: