Adding time in hours to a date object in java?

10,282

Solution 1

If you are using java.time it can be more helpful :

LocalDateTime dateStart = LocalDateTime.now();
LocalDateTime dateStop = dateStart.plusHours(4);

To format the date you can use :

String d1 = dateStart.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
String d2 = dateStop.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));

Solution 2

like others, i'd recommend using java.time if that's an option. the APIs are more consistent, and do a better job of catering to these types of operations.

however, to answer your question as-is... one option is to adjust the millisecond form of the Date instance by using get/setTime() as follows:

@Test
public void adjustTime() {
    final Date date = new Date();

    System.out.println("## Before adding four hours: " + date);

    date.setTime(date.getTime() + TimeUnit.HOURS.toMillis(4));

    System.out.println("## After adding four hours: " + date);
}

hope that helps!

Solution 3

Well there are several ways to do

Using Calendar class

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

If you are using ApacheCOmmon Lang

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

If you are using Joda-time

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

and if you are using Java 8 best would be LocalDateTime

LocalDateTime startDate = LocalDateTime.now();
LocalDateTime stopdate = startDate.plusHours(4);

Solution 4

tl;dr

  • Never use Date or SimpleDateFormat classes.
  • Use only modern java.time classes.

Example code:

LocalDateTime.parse(          // Parsing input string to an object without concept of zone or offset.
    "18/01/23 12:34:56" ,     // Input lacking indicator of zone/offset.
    DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" )  // Define formatting pattern matching your input.
)
.plusHours( 4 )               // Add four hours. Generating a new `LocalDateTime` object, per immutable objects pattern.
.toString()                   // Generate a String in standard ISO 8601 format.

2018-01-23T16:34:56

java.time

The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Never use Date, Calendar, SimpleDateFormat.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) ;

Unzoned

Apparently your input lacks an indicator of time zone or offset-from-UTC. So parse as a LocalDateTime.

LocalDateTime ldt = LocalDateTime.parse( "18/01/23 12:34:56" ) ; 

ldt.toString(): 2018-01-23T12:34:56

A LocalDateTime has no concept of time zone or offset-from-UTC. So it does not represent an actual moment, and is not a point on the timeline. A LocalDateTime is only a rough idea about potential moments along a range of about 26-27 hours.

Zoned

If you know for certain the input data was intended to represent a moment in a particular zone, apply a ZoneId to produce a ZonedDateTime. A ZonedDateTime does represent an actual moment, a point on the timeline.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  // Determining an actual moment.

zdt.toString(): 2018-01-23T12:34:56+01:00[Africa/Tunis]

To see the same moment in UTC, extract an Instant.

Instant instant = zdt.toInstant() ;

Math

Represent a span of time unattached to the timeline as a Duration object.

Duration d = Duration.ofHours( 4 ) ;  // Four hours, as an object.

Add to your LocalDateTime, if not using time zones.

LocalDateTime ldtLater = ldt.plus( d ) ;

If using zoned values, add to your ZonedDateTime.

ZonedDateTime zdtLater = zdt.plus( d ) ; 

Those classes also offer shortcut methods, if you wish.

ZonedDateTime zdtLater = zdt.plusHours( 4 ) ;  // Alternative to using `Duration` object.

One benefit of using a Duration rather than the shortcut methods is having an object that can be named.

Duration halfShiftLater = Duration.ofHours( 4 ) ;
…
ZonedDateTime zdtLater = zdt.plus( halfShiftLater ) ; 

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.

Share:
10,282
Neha
Author by

Neha

Updated on July 30, 2022

Comments

  • Neha
    Neha almost 2 years

    How do i add hours to a date object. Below is my code:

    String dateStart = timeStamp;
    String dateStop = valueCon;
    
    SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
    
    Date d1 = null;
    Date d2 = null;
    
    d1 = format.parse(dateStart);
    d2 = format.parse(datestop);
    

    I want to add 4 hours to d2 date object. How do i achieve it?

    I tried to use :

    Date modd1= new Date(d2+TimeUnit.MINUTES.toHours(240));
    

    But it accepts only long object for adding. Thus failed.

    Please support to solve this.Thanks in advance.

  • homerman
    homerman about 6 years
    the question asked, and answered, was "I want to add 4 hours to d2 date object. How do i achieve it?", which clearly has nothing to do with parsing.
  • Basil Bourque
    Basil Bourque about 6 years
    You’re right, I stand corrected.
  • Belphegor
    Belphegor almost 4 years
    Brilliant answer.
  • imp
    imp over 2 years
    Thats a beautiful answer