add Year to date - Android java.util

Android examples for java.util:Year

Description

add Year to date

Demo Code

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   w w w . j a  v  a  2s .c  om*/
   * <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 years ago or after few years
   * @param before or after year
   * @return yyyy-MM-dd
   */
  public static String addYear(int moveYear) {
      Calendar calendar = Calendar.getInstance();
      return addYear(format(FULL_DATE, calendar.getTime()), moveYear,
              FULL_DATE);
  }
  /**
   * <br>
   * From 'dateString' to a few years ago or after few years
   * @param dateStr
   * @param efore or after year
   * @return yyyy-MM
   */
  public static String addYear(String dateStr, int moveYear) {
      return addYear(dateStr, moveYear, YEAR_MONTH);
  }
  /**
   * <br>
   * From 'dateString' after few years
   * @param dateStr
   * @param add year
   * @param format (putForamt equal outputForamt)
   * @return format
   */
  public static String addYear(String dateStr, int addYear, String format) {
      return addYear(dateStr, addYear, format, format);
  }
  /**
   * <br>
   * From 'dateString' after few years
   * @param dateStr
   * @param add year
   * @param inFormat
   * @param outFormat
   * @return
   */
  public static String addYear(String dateStr, int addYear,
          String inFormat, String outFormat) {
      try {
          Date date = new SimpleDateFormat(inFormat).parse(dateStr);

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

Related Tutorials