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 LocalDate
by defaulting the day of the week to day-1.
public class Main {
public static void main(String[] args) {
String strWeekA = "2012-W48";
String strWeekB = "2013-W03";
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("YYYY-'W'ww")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date1 = LocalDate.parse(strWeekA, dtf);
LocalDate date2 = LocalDate.parse(strWeekB, dtf);
System.out.println(WEEKS.between(date1, date2));
}
}
Output:
7
Online Demo
Using an external library (original solution)
You can use the ThreeTen-Extra library for your requirements.
You can use YearWeek
, and its isBefore
and isAfter
methods.
You can use java.time.temporal.ChronoUnit#between
to calculate the amount of time between two YearWeek
objects. Alternatively, you can use YearWeek#until
to get the same result.
Given below is the Maven dependency for it:
<dependency>
<groupId>org.threeten</groupId>
<artifactId>threeten-extra</artifactId>
<version>1.7.2</version>
</dependency>
Demo:
import org.threeten.extra.YearWeek;
import static java.time.temporal.ChronoUnit.WEEKS;
public class Main {
public static void main(String[] args) {
String strWeekA = "2012-W48";
String strWeekB = "2013-W03";
YearWeek weekA = YearWeek.parse(strWeekA);
YearWeek weekB = YearWeek.parse(strWeekB);
System.out.println(weekA.isBefore(weekB));
System.out.println(WEEKS.between(weekA, weekB));
System.out.println(weekA.until(weekB, WEEKS));
}
}
Output:
true
7
7
new DateTimeFormatterBuilder().appendPattern("YYYY-'W'ww").parseDefaulting(ChronoField.DAY_OF_WEEK, 1).toFormatter()
instead ofISO_WEEK_DATE
– Leadership