Hello
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 time from the database by minutes, hours or days and then update the respective columns in the database.
I'm currently using Java.sql.date and java.sql.time types in Java. Can anyone suggest the best method for this?
I can achieve the above by the following:
public static String addToDateTime(String timestampIn, String increment) {
// Decompose timestamp.
int year = Integer.parseInt(timestampIn.substring(0, 4));
int month = Integer.parseInt(timestampIn.substring(5, 7));
int day = Integer.parseInt(timestampIn.substring(8, 10));
int hours = Integer.parseInt(timestampIn.substring(11, 13));
int mins = Integer.parseInt(timestampIn.substring(14, 16));
int secs = Integer.parseInt(timestampIn.substring(17, 19));
Calendar calendar = new GregorianCalendar(year, month - 1, day, hours, mins, secs);
// Increment timestamp.
if (increment.equals("HOURLY")) {
calendar.add(Calendar.HOUR, 1);
}
else if (increment.equals("DAILY")) {
calendar.add(Calendar.HOUR, 24);
}
else if (increment.equals("WEEKLY")) {
calendar.add(Calendar.HOUR, 168);
}
else if (increment.equals("DO NOT POLL")) {
// Do nothing.
}
// Compose new timestamp.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestampOut = sdf.format(calendar.getTime());
return timestampOut;
}
But would prefer something less primitive.
Thanks
Mr Morgan