add value to a Calendar - Java java.util

Java examples for java.util:Calendar Add

Description

add value to a Calendar

Demo Code

import java.util.Calendar;
import java.util.Date;

public class Main {
  public static void main(String[] argv) {
    Date date = new Date();
    String formatStr = "yyyy";
    int num = 42;
    System.out.println(addDateTime(date, formatStr, num));
  }//from  w w w.  jav  a2  s  .c o m

  public static Date addDateTime(Date date, String formatStr, int num) {

    if (date != null && formatStr != null) {
      Calendar calender = Calendar.getInstance();
      calender.setTime(date);
      if (formatStr.equals("yyyy")) {
        calender.add(Calendar.YEAR, num);
      } else if (formatStr.equals("MM")) {
        calender.add(Calendar.MARCH, num);
      } else if (formatStr.equals("dd")) {
        calender.add(Calendar.DATE, num);
      } else if (formatStr.equals("hh")) {
        calender.add(Calendar.HOUR, num);
      } else if (formatStr.equals("mm")) {
        calender.add(Calendar.MINUTE, num);
      } else if (formatStr.equals("ss")) {
        calender.add(Calendar.SECOND, num);
      }
      return calender.getTime();
    }
    return null;
  }
}

Related Tutorials