167

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.

Reimius
  • 5,694
  • 5
  • 24
  • 42
Jorge Lainfiesta
  • 1,671
  • 2
  • 10
  • 3
  • 3
    Use http://joda-time.sourceforge.net/, if possible. – Babar Aug 27 '10 at 05:03
  • 3
    Use [Java 8 Date](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) and Time if possible. – peceps Aug 18 '16 at 14:12
  • @Babar FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [*java.time*](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 25 '18 at 18:49

16 Answers16

236

Check Calendar class. It has add method (and some others) to allow time manipulation.

Something like this should work:

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date());               // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1);      // adds one hour
cal.getTime();                         // returns new date object plus one hour

Check API for more.

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
  • 4
    Just be careful if you're dealing with daylight savings/summer time. – CurtainDog Aug 27 '10 at 04:26
  • 7
    Needless to mention you can add "negative hours" – pramodc84 Aug 27 '10 at 05:56
  • 6
    @CurtainDog Using `Calendar.add()` takes care of that automatically. – Jesper Aug 27 '10 at 10:05
  • 7
    cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale." – mithrandir Dec 10 '14 at 09:54
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 25 '18 at 18:48
  • Doesn't work anymore: "The method setTime(Date) in the type Calendar is not applicable for the arguments (Object)" – TheJeff Apr 09 '21 at 16:06
96

If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():

Date newDate = DateUtils.addHours(oldDate, 3);

(The original object is unchanged)

Script47
  • 14,230
  • 4
  • 45
  • 66
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 3
    You can also use negativ Hours: `DateUtils.addHours(oldDate, -1);` – Kaptain Feb 24 '15 at 10:54
  • Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not? – Matt Feb 13 '18 at 16:01
38

To simplify @Christopher's example.

Say you have a constant

public static final long HOUR = 3600*1000; // in milli-seconds.

You can write.

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

If you use long to store date/time instead of the Date object you can do

long newDate = oldDate + 2 * HOUR;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
30

tl;dr

myJavaUtilDate.toInstant()
              .plusHours( 8 )

Or…

myJavaUtilDate.toInstant()                // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
              .plus(                      // Do the math, adding a span of time to our moment, our `Instant`. 
                  Duration.ofHours( 8 )   // Specify a span of time unattached to the timeline.
               )                          // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.

Using java.time

The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.

Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.

Instant instant = myUtilDate.toInstant();

You can add hours to that Instant by passing a TemporalAmount such as Duration.

Duration duration = Duration.ofHours( 8 );
Instant instantHourLater = instant.plus( duration );

To read that date-time, generate a String in standard ISO 8601 format by calling toString.

String output = instantHourLater.toString();

You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.

ZonedDateTime later = zdt.plusHours( 8 );

You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.

java.util.Date date = java.util.Date.from( later.toInstant() );

For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
24

With Joda-Time

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Babar
  • 2,786
  • 3
  • 25
  • 35
  • 2
    +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library – Joeri Hendrickx Aug 27 '10 at 08:16
  • 3
    @JoeriHendrickx If the programmer is adding hours to a date, then *very* likely they are doing other date-time work. I don’t consider [Joda-Time](http://www.joda.org/joda-time/) unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new [java.time.* package](http://download.java.net/jdk8/docs/api/java/time/package-summary.html) (inspired by Joda-Time) to Java 8. – Basil Bourque Feb 17 '14 at 06:14
  • I had trouble with Joda on android. Kept getting `ClassNotDefinedException` – TheRealChx101 Nov 08 '15 at 17:39
23

Using the newish java.util.concurrent.TimeUnit class you can do it like this

Date oldDate = new Date(); // oldDate == current time
Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Add 2 hours
ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
Iain
  • 582
  • 5
  • 12
23

Since Java 8:

LocalDateTime.now().minusHours(1);

See LocalDateTime API.

leventov
  • 14,760
  • 11
  • 69
  • 98
  • 4
    Close but not quite right. You should go for a `ZonedDateTime` rather than a `LocalDateTime`. The "Local" means *not* tied to any particular locality, and *not* tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See [my Answer](http://stackoverflow.com/a/33021219/642706) by comparison. – Basil Bourque Oct 08 '15 at 16:37
  • 1
    Also to get a `java.util.Date` object as requester had asked us `ZonedDateTime.toInstant()` and `Date.from()` as described here https://stackoverflow.com/a/32274725/5661065 – hayduke Oct 18 '17 at 00:28
17

Something like:

Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() + 
                        (2L * hoursInMillis)); // Adds 2 hours
Christopher Hunt
  • 2,071
  • 1
  • 16
  • 20
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 25 '18 at 18:48
8

This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.

    String myString =  "09:00 12/12/2014";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
    Date myDateTime = null;

    //Parse your string to SimpleDateFormat
    try
      {
        myDateTime = simpleDateFormat.parse(myString);
      }
    catch (ParseException e)
      {
         e.printStackTrace();
      }
    System.out.println("This is the Actual Date:"+myDateTime);
    Calendar cal = new GregorianCalendar();
    cal.setTime(myDateTime);

    //Adding 21 Hours to your Date
    cal.add(Calendar.HOUR_OF_DAY, 21);
    System.out.println("This is Hours Added Date:"+cal.getTime());

Here is the Output:

    This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
    This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014
vkrams
  • 7,267
  • 17
  • 79
  • 129
5

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();
RaT
  • 1,134
  • 3
  • 12
  • 28
4
Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);
Ghost Rider
  • 161
  • 1
  • 1
  • 10
4

If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:

import java.time.Duration;
import java.time.LocalDateTime;

...

LocalDateTime yourDate = ...

...

// Adds 1 hour to your date.

yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
// OR
yourDate = yourDate + Duration.parse("PT1H"); // Groovy.  
Daniel
  • 8,655
  • 5
  • 60
  • 87
  • 1
    `Duration.parse(iso8601duration)` is interesting, thanks, but you cannot use operator `+` on `LocalDateTime`, you might want to edit that. But `.plus(...)` does work. – qlown May 24 '17 at 22:42
  • Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly. – Daniel May 24 '17 at 22:49
  • The Question is about a `Date` object, which represent a specific moment in UTC. Your use of `LocalDateTime` fails to address the Question. `LocalDateTime` lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See [*What's the difference between Instant and LocalDateTime?*](https://stackoverflow.com/q/32437550/642706) – Basil Bourque Mar 28 '19 at 22:11
  • @BasilBourque `Date` object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out `LocalDateTime` for `ZonedDateTime`. – Daniel Mar 28 '19 at 23:12
1

by using Java 8 classes. we can manipulate date and time very easily as below.

LocalDateTime today = LocalDateTime.now();
LocalDateTime minusHours = today.minusHours(24);
LocalDateTime minusMinutes = minusHours.minusMinutes(30);
LocalDate localDate = LocalDate.from(minusMinutes);
Abdul Gafoor
  • 913
  • 10
  • 12
  • The Question is about a `Date` object, which represent a specific moment in UTC. Your use of `LocalDateTime` fails to address the Question. `LocalDateTime` lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See [*What's the difference between Instant and LocalDateTime?*](https://stackoverflow.com/q/32437550/642706) – Basil Bourque Mar 28 '19 at 22:08
0

You can use the LocalDateTime class from Java 8. For eg :

long n = 4;
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.plusHours(n));
Sajit Gupta
  • 98
  • 1
  • 6
  • 1
    The Question is about a `Date` object, which represent a specific moment in UTC. Your use of `LocalDateTime` fails to address the Question. `LocalDateTime` lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See [*What's the difference between Instant and LocalDateTime?*](https://stackoverflow.com/q/32437550/642706) – Basil Bourque Mar 28 '19 at 22:10
0

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));
Sameera De Silva
  • 1,722
  • 1
  • 22
  • 41
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Nov 22 '21 at 17:17
-2

You can use this method, It is easy to understand and implement :

public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
    calendar.add(Calendar.MINUTE, nombreMinute);
    calendar.add(Calendar.SECOND, nombreSeconde);
    return calendar.getTime();
}
Nimpo
  • 430
  • 6
  • 13
  • 1
    This approach is already presented in [another Answer](http://stackoverflow.com/a/3581278/642706) posted years ago. I do not see how this one adds anymore value. – Basil Bourque Jan 13 '17 at 17:37
  • The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :) – Nimpo Jan 15 '17 at 12:12