How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.
How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.
This code worked in Java 8.No additional libraries were not needed.
public static String getCurrentDatetimePlusNoOfHours(int numberOfHours) {
String futureDay = getCurrentDatetime(); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(futureDay));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.HOUR, numberOfHours); // number of hours to add, if it's minus send - value like -4
futureDay = sdf.format(c.getTime()); // dt is now the new date
return futureDay;
}
Call the method
getCurrentDatetimePlusNoOfHours(4));