Add X hours to a date & time

user2911924 picture user2911924 · May 9, 2014 · Viewed 17.8k times · Source

I am currently fetching the time and date trough:

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

This returns the example '05/14/2014 01:10:00'

Now I am trying to make it so I can add a hour to this time without having to worry about a new day or month etc.

How would I go on getting '05/14/2014 01:10:00' but then for 10 hours later in the same format?

Thanks in advance.

Answer

Robert Durgin picture Robert Durgin · May 9, 2014

Look at the Calendar object: Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 10);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(dateFormat.format(cal.getTime()));