Java examples for java.util:Month
add Months
//package com.java2s; 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 void main(String[] argv) throws Exception { Date date = new Date(); int months = 2; System.out.println(addMonths(date, months)); }//w ww.j a v a2 s .c om 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 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 String getDateSplit() { return "."; } }