javadatetimecalendarforward

Add X hours to a date & time


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.


Solution

  • 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()));