Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;

public class Main {
    public static void main(String[] argv) {
        System.out.println(getQuarter(LocalDate.now()));
    }

    /**
     * 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;
        }
    }

}