I have an issue where I have a MySQL database storing dates and times in separate columns. However, in Java code I need to increment the resulting timestamp for a date and t
Here's an optimization, assuming that the input is java.util.Date
wherein you can just pass java.sql.Date
and java.sql.Time
in since they are just 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 the Sun tutorial on the subject. However, as per Java 7 you should be able to switch
on String
.
I however strongly agree the JodaTime advice, here's 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 has more advantages as well.