-1

I have two date periods in my invoice,

Total bill period - 6 Nov 2019 to 3 Feb 2020 (String)

price change period - 22 Jan 2020 to 3 Feb 2020 (String)

So the total bill period is for 90 days, in which there is a price change for 13 days from 22nd Jan 2020 to 3 Feb 2020.

I need to get the bill period for the non price change days which is - 6 Nov 2019 to 21 Jan 2020.

What is the best way to get the difference between these dates ?

Thanks in advance!

alex
  • 147
  • 1
  • 4
  • 17
  • 3
    It is unclear what your data is. Do you have the dates as strings in exactly the given format? Is there only ever one price change period per bill period? – Felix Dombek Mar 10 '20 at 00:13
  • 1
    You probably want [Period.between](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/Period.html#between%28java.time.LocalDate,java.time.LocalDate%29). – VGR Mar 10 '20 at 00:38
  • @VGR Or for *the total bill period is for 90 days* perhaps `ChronoUnit.DAYS.between()`. In any case it’s all in the answers to the linked original question. – Ole V.V. Mar 10 '20 at 04:19
  • @Felix Yes only one price change.. – alex Mar 10 '20 at 05:49

1 Answers1

-1

Assuming the assumptions in my comment hold, and you have strings like this:

String billPeriodStart   = "6 Nov 2019";
String billPeriodEnd     = "3 Feb 2020";
String changePeriodStart = "22 Jan 2020";
String changePeriodEnd   = "3 Feb 2020";

Something like this might work (untested):

SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
Date billPeriodStartDate = dateFormat.parse(billPeriodStart);
// same for the other values

Calendar cal = Calendar.getInstance();

cal.setDate(changePeriodStartDate);
cal.add(Calendar.DAY, -1);
Date dateBeforeChangePeriod = cal.getTime();

cal.setDate(changePeriodEndDate);
cal.add(Calendar.DAY, 1);
Date dateAfterChangePeriod = cal.getTime();

boolean hasDaysBeforeChangePeriod = !dateBeforeChangePeriod.before(billPeriodStartDate);
boolean hasDaysAfterChangePeriod  = !dateAfterChangePeriod.after(billPeriodEndDate);

if (hasDaysBeforeChangePeriod) {
  // print billPeriodStartDate to dateBeforeChangePeriod 
}
if (hasDaysAfterChangePeriod) {
  // print dateAfterChangePeriod to billPeriodEndDate
}
if (!hasDaysBeforeChangePeriod && !hasDaysAfterChangePeriod) {
  // print "none"
}
Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Mar 10 '20 at 04:02