Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;

public class Main {
    /**
     * Calculates how many months are in given period. If one of the dates only partially covers the month, it still counts as full month.
     *
     * @param start Start of the period.
     * @param end   End of the period.
     * @return Number of days in given period. If {@code end < start}, returns -1.
     */
    public static int getMonthCountInPeriod(long start, long end) {
        if (end < start)
            return -1;

        final Calendar cal = Calendar.getInstance();
        final int monthCountInYear = cal.getMaximum(Calendar.MONTH);

        cal.setTimeInMillis(start);
        final int startYear = cal.get(Calendar.YEAR);
        final int startMonth = cal.get(Calendar.MONTH) + 1;

        cal.setTimeInMillis(end);
        final int endYear = cal.get(Calendar.YEAR);
        final int endMonth = cal.get(Calendar.MONTH) + 1;

        int monthsCount;

        if (startYear != endYear) {
            monthsCount = monthCountInYear * Math.max(0, endYear - startYear - 1);
            monthsCount += monthCountInYear - startMonth + 1;
            monthsCount += endMonth;
        } else {
            monthsCount = endMonth - startMonth + 1;
        }

        return monthsCount;
    }
}