Periodを使用すると、これをかなり簡単に計算できます。ここでは例です:
public static boolean isWithinAWeek(LocalDate dueDate) {
boolean result = false;
LocalDate today = LocalDate.now();
System.out.println("Today is " + today);
System.out.println("Due Date is " + dueDate);
Period p = Period.between(today, dueDate);
System.out.println("The period between these two is " + p.getYears() + " years, " + p.getMonths() +" months, " + p.getDays() + " days.");
// do you want to measure a week backwards? If so, change "p.getDays() >= 0" to "p.getDays() >= -7"
if (p.getYears() == 0 && p.getMonths() == 0 && p.getDays() >= 0 && p.getDays() <= 7) {
System.out.println(String.format(" └─ Yes, %1$s is within a week from %2$s.", dueDate, today));
result = true;
} else {
System.out.println(String.format(" └─ No, %1$s is NOT within a week from %2$s.", dueDate, today));
result = false;
}
return result;
}
は、以下のようにして、これを呼び出す:
public static void main(String[] args) {
LocalDate due;
// 7 days from now
due = LocalDate.of(2017, Month.OCTOBER, 15);
System.out.println(isWithinAWeek(due));
System.out.println();
// 8 days from now
due = LocalDate.of(2017, Month.OCTOBER, 16);
System.out.println(isWithinAWeek(due));
System.out.println();
// a month from now
due = LocalDate.of(2017, Month.NOVEMBER, 8);
System.out.println(isWithinAWeek(due));
System.out.println();
// 5 days ago
due = LocalDate.of(2017, Month.OCTOBER, 3);
System.out.println(isWithinAWeek(due));
}
には、次のものが得られます:
Today is 2017-10-08
Due Date is 2017-10-15
The period between these two is 0 years, 0 months, 7 days.
└─ Yes, 2017-10-15 is within a week from 2017-10-08.
true
Today is 2017-10-08
Due Date is 2017-10-16
The period between these two is 0 years, 0 months, 8 days.
└─ No, 2017-10-16 is NOT within a week from 2017-10-08.
false
Today is 2017-10-08
Due Date is 2017-11-08
The period between these two is 0 years, 1 months, 0 days.
└─ No, 2017-11-08 is NOT within a week from 2017-10-08.
false
Today is 2017-10-08
Due Date is 2017-10-03
The period between these two is 0 years, 0 months, -5 days.
└─ No, 2017-10-03 is NOT within a week from 2017-10-08.
false
コードが正しいかどうかを確認する最も良い方法は、単体テストケースを書いたり、異なる値を渡してチェックすることです。物事が期待どおりに機能しない場合は、私たちに知らせてください:) – Nishit