Java Month Calculate getMonthsOfAge(Date birth, Date now)

Here you can find the source of getMonthsOfAge(Date birth, Date now)

Description

get Months Of Age

License

Open Source License

Declaration

public static int getMonthsOfAge(Date birth, Date now) 

Method Source Code

//package com.java2s;
/*/*from  ww w .j  av  a2 s . co  m*/
 * #%L
 * Webstar Newsletter
 * %%
 * Copyright (C) 2013 Webstar Csoport Kft.
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import java.util.*;

public class Main {

    public static int getMonthsOfAge(Date birth, Date now) {
        Calendar nowCalendar = new GregorianCalendar();
        Calendar birthCalendar = new GregorianCalendar();
        birthCalendar.setTime(birth);
        nowCalendar.setTime(now);
        if (nowCalendar.getTimeInMillis() > birthCalendar.getTimeInMillis()) {
            int months = nowCalendar.get(Calendar.MONTH) - birthCalendar.get(Calendar.MONTH);
            int yearDiff = nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
            if (yearDiff > 0) {
                months = yearDiff * 12 + months;
            }
            if (nowCalendar.get(Calendar.DAY_OF_MONTH) < birthCalendar.get(Calendar.DAY_OF_MONTH)) {
                months--;
            }
            return months;
        } else {
            return 0;
        }
    }
}

Related

  1. getLastMonthBegin()
  2. getMonthFormat(String date)
  3. getMonthlyIntervals(Date start, Date end)
  4. getMonthNumber()
  5. getMonthsMap()
  6. getMonthSpan(Date begin, Date end)
  7. getNextMonth(long date)
  8. getNextMonthExtention(Date dt, Long n)
  9. getNowMonth()