I am having fromDate
as "01-Jan-2015"
and toDate
as "01-Apr-2015"
. I want to find number of quarters between fromDate
and toDate
. My code is like
String fromDate = "01-Jan-2015";
String toDate = "01-Apr-2015";
ArrayList<String> quarters = new ArrayList<String>();
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
DateFormat dfYY = new SimpleDateFormat("yy");
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(fromDate));
Calendar cal1 = Calendar.getInstance();
cal1.setTime(df.parse(toDate));
while (cal1.getTime().after(cal.getTime())) {
int month = cal.get(Calendar.MONTH) + 1;
int quarter = month % 3 == 0 ? (month / 3) : (month / 3) + 1;
quarters.add("Q" + quarter + "-" + dfYY.format(cal.getTime()));
cal.add(Calendar.MONTH, 3);
}
But it is giving output as Q1-15, Q2-15 is missing. If I enter toDate
as"02-Apr-2015" then it is giving Q1-15, Q2-15. Please help me where I am going wrong.
IsoFields.QUARTER_YEARS
A special unit exists for this purpose in Java 8 and later: java.time.temporal.IsoFields.QUARTER_YEARS
implementing TemporalUnit
and its between
method.
long delta =
IsoFields.QUARTER_YEARS.between(
LocalDate.of(2015, 1, 1),
LocalDate.of(2015, 4, 1));
System.out.println(delta); // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With