Add X hours to a date & time

18,430

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
18,430
user2911924
Author by

user2911924

Updated on June 04, 2022

Comments

  • user2911924
    user2911924 almost 2 years

    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.