add Month value to date value - Android java.util

Android examples for java.util:Month

Description

add Month value to date value

Demo Code

import android.annotation.SuppressLint;
import android.text.format.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main{
  public static final String YEAR = "yyyy";
  public static final String MONTH = "MM";
  public static final String DAY = "dd";
  public static final String FULL_TIME = "HH:mm:ss";
  public static final String YEAR_MONTH = YEAR + "-" + MONTH;
  public static final String FULL_DATE = YEAR_MONTH + "-" + DAY;
  public static final String FULL_DATE_TIME = FULL_DATE + " " + FULL_TIME;
  public static final String FULL_TIME_ZONE = FULL_DATE + "'T'"
          + FULL_TIME + "'Z'";

  /**//from  ww  w . j a  v a2  s.  co m
   * <br>
   * Convert date format
   * @param format
   * @param date
   * @return String
   */
  private static String format(String format, Date date) {
      SimpleDateFormat f = new SimpleDateFormat(format);
      return f.format(date);
  }
  /**
     * <br>
     * From now to a few months ago or after few months
     * @param after or before month
     * @return yyyy-MM-dd
     */
    public static String addMonth(int moveMonth) {
        Calendar calendar = Calendar.getInstance();
        return addMonth(format(FULL_DATE, calendar.getTime()), moveMonth,
                FULL_DATE);
    }
    /**
     * <br>
     * From 'dateStr' to a few months ago or after few months
     * @param dateStr
     * @param move month
     * @return yyyy-MM
     */
    public static String addMonth(String dateStr, int moveMonth) {
        return addMonth(dateStr, moveMonth, YEAR_MONTH);
    }
    /**
     * <br>
     * From 'dateStr' after few months
     * @param dateStr
     * @param move month
     * @param format
     * @return format
     */
    public static String addMonth(String dateStr, int moveMonth,
            String format) {
        return addMonth(dateStr, moveMonth, format, format);
    }
    /**
     * <br>
     * From 'dateStr' after few months
     * @param dateStr
     * @param move month
     * @param inFormat
     * @param outFormat
     * @return
     */
    public static String addMonth(String dateStr, int moveMonth,
            String inFormat, String outFormat) {
        try {
            Date date = new SimpleDateFormat(inFormat).parse(dateStr);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)
                    + moveMonth);
            return format(outFormat, calendar.getTime());
        } catch (ParseException e) {
            return dateStr;
        }
    }

}

Related Tutorials