Here you can find the source of addMonths2(String dateStr, int months)
public static String addMonths2(String dateStr, int months)
//package com.java2s; //License from project: Apache License import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.StringTokenizer; public class Main { public static String addMonths2(String dateStr, int months) { Date date = getStrDateToDate(dateStr); date = addMonths(date, months);//from w ww .j av a 2 s.com date = addDays(date, -1); SimpleDateFormat formatter; formatter = new SimpleDateFormat("yyyy" + getDateSplit() + "MM" + getDateSplit() + "dd"); String dateString = formatter.format(date); return dateString.trim(); } public static Date getStrDateToDate(String dateStr) { String dateSplit = getDateSplit(); if (dateSplit.equals(".")) dateSplit = "\\."; StringTokenizer filter = new StringTokenizer(dateStr, dateSplit); int year = Integer.parseInt(filter.nextToken()); int mon = Integer.parseInt(filter.nextToken()) - 1; int day = Integer.parseInt(filter.nextToken()); Calendar cal = new GregorianCalendar(year, mon, day); return cal.getTime(); } public static Date addMonths(Date date, int months) { Calendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(Calendar.MONTH, months); return cal.getTime(); } public static String addMonths(String dateStr, int months) { Date date = getStrDateToDate(dateStr); date = addMonths(date, months); SimpleDateFormat formatter; formatter = new SimpleDateFormat("yyyy" + getDateSplit() + "MM" + getDateSplit() + "dd"); String dateString = formatter.format(date); return dateString.trim(); } public static Date addDays(Date date, int days) { Calendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(Calendar.DATE, days); return cal.getTime(); } public static String addDays(String dateStr, int days) { Date date = getStrDateToDate(dateStr); date = addDays(date, days); SimpleDateFormat formatter; formatter = new SimpleDateFormat("yyyy" + getDateSplit() + "MM" + getDateSplit() + "dd"); String dateString = formatter.format(date); return dateString.trim(); } public static String getDateSplit() { return "."; } }