Calculates the number of quarters between two given dates - Java java.time

Java examples for java.time:Quarter

Description

Calculates the number of quarters between two given dates

Demo Code


//package com.java2s;

import java.time.LocalDate;

import java.time.Month;

import java.time.temporal.ChronoField;

public class Main {
    /**//from  ww  w  .  j a v  a 2s. c o  m
     * Calculates the number of quarters between two given dates
     * 
     * @return Number of quarters
     * @param date1
     *            First given date cannot be null
     * @param date2
     *            Second given date cannot be null
     */
    public static int getQuartersBetweenDates(LocalDate date1,
            LocalDate date2) {
        LocalDate beginn = null;
        LocalDate end = null;
        if (date1.isBefore(date2)) {
            beginn = date1;
            end = date2;
        } else {
            beginn = date2;
            end = date1;
        }
        int quarters = getQuarter(end) - getQuarter(beginn);
        int years = end.get(ChronoField.YEAR)
                - beginn.get(ChronoField.YEAR);
        quarters += years * 4;
        return Math.abs(quarters);
    }

    /**
     * Returns the current quarter of the given date
     * 
     * @return int (0 .. 3)
     * @param cal
     *            Given date, cannot be null
     */
    public static int getQuarter(LocalDate cal) {
        int month = cal.get(ChronoField.MONTH_OF_YEAR);
        switch (Month.of(month)) {
        case JANUARY:
        case FEBRUARY:
        case MARCH:
        default:
            return 0;
        case APRIL:
        case MAY:
        case JUNE:
            return 1;
        case JULY:
        case AUGUST:
        case SEPTEMBER:
            return 2;
        case OCTOBER:
        case NOVEMBER:
        case DECEMBER:
            return 3;
        }
    }
}

Related Tutorials