Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of quarters between two dates in Java

Tags:

java

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.

like image 773
Sarvesh V Avatar asked Mar 17 '23 14:03

Sarvesh V


1 Answers

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
like image 186
Meno Hochschild Avatar answered Apr 01 '23 10:04

Meno Hochschild