Adding n hours to a date in Java?

2019-01-02 20:39发布

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 date
15条回答
萌妹纸的霸气范
2楼-- · 2019-01-02 21:07

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;
查看更多
与君花间醉酒
3楼-- · 2019-01-02 21:07

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)); // Adds 2 hours
查看更多
栀子花@的思念
4楼-- · 2019-01-02 21:13

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)

查看更多
泛滥B
5楼-- · 2019-01-02 21:15

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
查看更多
冷夜・残月
6楼-- · 2019-01-02 21:17

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.

查看更多
笑指拈花
7楼-- · 2019-01-02 21:17

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.  
查看更多
登录 后发表回答