Here's an optimization, assuming the input is java.util.Date , in which you can just pass java.sql.Date and java.sql.Time , since they are its subclasses.
public static String addToDateTime(Date date, Increment increment) throws ParseException { Calendar calendar = calendar.getInstance(); calendar.clear(); calendar.setTime(date); switch (increment) { case HOURLY: calendar.add(Calendar.HOUR, 1); break; case DAILY: calendar.add(Calendar.DATE, 1); break; case WEEKLY: calendar.add(Calendar.WEEK_OF_YEAR, 1); break; case DO_NOT_POLL: break; } return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()); } public enum Increment { HOURLY, DAILY, WEEKLY, DO_NOT_POLL; }
which can be used as
String newTimestamp = addToDateTime(timestampIn, Increment.WEEKLY);
To learn more about the useful enum , check out Sun's tutorial on this . However, according to Java 7, you must be able to switch to String .
However, I strongly agree with the JodaTime recommendation, here is an example:
public static String addToDateTime(Date date, Increment increment) { DateTime dt = new DateTime(date); switch (increment) { case HOURLY: dt = dt.plusHours(1); break; case DAILY: dt = dt.plusDays(1); break; case WEEKLY: dt = dt.plusWeeks(1); break; case DO_NOT_POLL: break; } return df.print(dt); } public enum Increment { HOURLY, DAILY, WEEKLY, DO_NOT_POLL; }
The difference is admittedly not shocking, but it also has more advantages.
source share