Adding n hours to a date in Java?

JavaDate

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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)

Solution 3 - Java

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;

Solution 4 - Java

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.

Solution 5 - Java

With Joda-Time

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);

Solution 6 - Java

Since Java 8:

LocalDateTime.now().minusHours(1);

See LocalDateTime API.

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

Solution 12 - Java

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.  

Solution 13 - Java

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

Solution 14 - Java

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

long n = 4;
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.plusHours(n));

Solution 15 - Java

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

Solution 16 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJorge LainfiestaView Question on Stackoverflow
Solution 1 - JavaNikita RybakView Answer on Stackoverflow
Solution 2 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 3 - JavaPeter LawreyView Answer on Stackoverflow
Solution 4 - JavaBasil BourqueView Answer on Stackoverflow
Solution 5 - JavaBabarView Answer on Stackoverflow
Solution 6 - JavaleventovView Answer on Stackoverflow
Solution 7 - JavaIainView Answer on Stackoverflow
Solution 8 - JavaChristopher HuntView Answer on Stackoverflow
Solution 9 - JavavkramsView Answer on Stackoverflow
Solution 10 - JavaGhost RiderView Answer on Stackoverflow
Solution 11 - JavaRaTView Answer on Stackoverflow
Solution 12 - JavaDanielView Answer on Stackoverflow
Solution 13 - JavaAbdul GafoorView Answer on Stackoverflow
Solution 14 - JavaSajit GuptaView Answer on Stackoverflow
Solution 15 - JavaSameera De SilvaView Answer on Stackoverflow
Solution 16 - JavaNimpoView Answer on Stackoverflow