get month between min Time and max Time, including head and tail - Java java.util

Java examples for java.util:Month

Description

get month between min Time and max Time, including head and tail

Demo Code


//package com.java2s;

import java.util.Calendar;

public class Main {
    /**/*from   w ww. j  a  v  a 2  s . c  o  m*/
     * get month between minTime and maxTime, including head and tail
     *
     * @param minTime
     * @param maxTime
     * @return
     */
    public static int getMonthNum(long minTime, long maxTime) {
        Calendar min = Calendar.getInstance();
        min.setTimeInMillis(minTime);
        Calendar max = Calendar.getInstance();
        max.setTimeInMillis(maxTime);
        if (max.before(min)) {
            throw new IllegalArgumentException(
                    "max date is before min date");
        }
        int minMonth = min.get(Calendar.MONTH) + 1;
        int maxMonth = max.get(Calendar.MONTH) + 1;
        return (max.get(Calendar.YEAR) - min.get(Calendar.YEAR)) * 12
                + maxMonth - minMonth + 1;
    }
}

Related Tutorials