Question

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.

Was it helpful?

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

OTHER TIPS

As others have mentioned, the Calendar class is designed for this.

As of Java 8, you can also do this:

DateTimeFormatter dateFormat =
    DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

LocalDateTime date = LocalDateTime.now();
System.out.println(dateFormat.format(date));
System.out.println(dateFormat.format(date.plusHours(10)));

java.time.format.DateTimeFormatter uses a lot of the same pattern letters as java.text.SimpleDateFormat, but they are not all the same. See the DateTimeFormatter javadoc for the details.

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = new Date();
final long reqHoursInMillis = 1 * 60 * 60 * 1000;  // change 1 with required hour
Date newDate = new Date(currentDate.getTime() + reqHoursInMillis);
System.out.println(dateFormat.format(newDate));

This will add 1 hour in current time in the given date format. Hope it helps.

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

/*
 * Add x hours to the time
 */

int x = 10;

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

calendar.add(Calendar.HOUR, x);

System.out.println(dateFormat.format(calendar.getTime()));

Console output:

05/08/2014 20:34:18
05/09/2014 06:34:18
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top