×

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us to address a particular time on the course of events utilizing java.time.Instant.In this instructional exercise, we'll figure out how to add or deduct n hours from a given date-time in java. We'll initially take a gander at some standard Java date-time-related classes, and afterward, we'll exhibit a couple of outsider choices. To become familiar with the Java 8 DateTime API

Ways to Add Time in Java

1. java.util.Date:

Assuming we're utilizing Java 7 or lower, we can utilize the java.util.Date and java.util.Calendar classes for most date-time related dealing with.

Assume we have a Java 8 application, yet at the same time, we need to work our direction with java.util.Date cases.

For such a case, we can pick to adopt the accompanying substitute strategy:

  1. Use java.util.Date toInstant() technique to change over a Date object to a java.time.Instant occasion
  2. Add a particular Duration to the java.time.Instant object utilizing the in addition to() technique
  3. Recuperate our java.util.Date example by passing in the java.time.Instant object to the java.util.Date.from() strategy

Example

Example program to add time in java using java.util.Calendar class:

// program to add time in java using java.util.Calendar class
import java.io.*;
import java.util.Calendar;
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
         // creating the object to the Calender class and calling the getInstance() method to get the current instance of time
      Calendar c = (Calendar) Calendar.getInstance();  
      // printing the current instance of time
      System.out.println(" The current date and time is: " + c.getTime());        
        // Adding ten years to the current date and time   
      c.add((Calendar.YEAR), 10);  
      // printing the date and time after adding 10 years
      System.out.println(" The date and time after 10 years is: " + c.getTime());  
    }
}

Output:

Add Time in Java

2. java.time.LocalDateTime/ZonedDateTime:

In Java 8 or later, adding hours to either a java.time.LocalDateTime or java.time.ZonedDateTime model is truly immediate and uses the plusHours() procedure:

plusHours() procedure for a ZonedDateTime class is utilized to add the quantity of hours in this ZonedDateTime and return a copy of ZonedDateTime after option. This deals with the second plan so much that adding one hour will continually be a length of one hour sometime later. Adding one hour could cause the local date time to change by an aggregate other than an hour.

Example

Example program to add time using java.time.LocalDateTime class

// program to add time in java using java.time.ZonedDateTime class.
import java.io.*;
import java.time.*;
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        // creating object to the ZonedDateTime class and calling the now() method to get the current instance of time
        ZonedDateTime time= ZonedDateTime.now();
        // printing the current time
        System.out.println(" The current date and time is: " + time);
        // adding 100 days to the current date and time using plus() method
        ZonedDateTime pan = time.plus(Period.ofDays(100));  
        // printing the time after adding 100 days
        System.out.println(" The date and time after adding 100 days to the current date and time: " + pan);  
    }
}

Output:

Add Time in Java

Example 2

Example program to add time using java.time.LocalDateTime class:

Java LocalDateTime class is a changeless date-time object that addresses a date-time, with the default design as yyyy-MM-dd-HH-mm-ss.zzz. It acquires the object class and executes the ChronoLocalDateTime interface.

// program to add time in java using java.time.LocalDateTime class.
import java.io.*;
import java.time.*;
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        // creating an object to the LocalDateTime class and calling the now() method to get the current instance of time
        LocalDateTime date = LocalDateTime.now(); 
        // printing the current date and time
        System.out.println(" The current date and time is: " + date);
        // adding 40 days to the current date and time using plusDays() method
        LocalDateTime date1 = date.plusDays(40);  
        // printing date and time after adding 40 days
        System.out.println(" The date and time after adding 40 days to the current date and time is: " + date1);
    }
}

Output:

Add Time in Java

3. java.time.Instant:

Java Instant class is utilized to address the particular second on the timetable. It acquires the Object class and executes the Comparable connection point.

As we probably are aware, java.time.Instant presented in Java 8 DateTime API addresses a particular second on the course of events. To add an hours to an Instant item, we can utilize it is in plus() strategy with a java.time.temporal.TemporalAmount:

Example: A program to add time using java.time.Instant class

// program to print the current date and time and add time to the current date and time using Instant class and its methods
import java.time.Instant;  
import java.time.temporal.ChronoUnit; 
import java.time.*;
class HelloWorld {
    public static void main(String[] args) {
       System.out.println("Hello, World!");
        // creating an object to the Instant class and calling the now() method to get the current instance of time
        Instant date = Instant.now(); 
        // printing the current date and time
        System.out.println(" The current date and time is: " + date);
        // creating another object to the Instant class to add time
        // adding 40 days to the current date and time using plus() method
        Instant date1 = date.plus(Duration.ofDays(40));  
        // printing date and time after adding 40 days
        System.out.println(" The date and time after adding 40 days to the current date and time is: " + date1);


    }
}

Output:

Add Time in Java

4. java.time.OffsetDateTime:

Java OffsetDateTime class is a changeless portrayal of a date-time with an offset. It acquires Object class and carries out the Comparable point of interaction. OffsetDateTime class is utilized to store the date and time fields to an accuracy of nanoseconds.

Example

Example program to add time using the java.time.OffsetDateTime class

// program to print the current date and time and add time to the current date and time using OffsetDateTime class and its methods
import java.time.OffsetDateTime;  
import java.time.*;
// importing the required packages and classes
class HelloWorld {
    public static void main(String[] args) {
       System.out.println("Hello, World!");
        // creating an object to the Instant class and calling the now() method to get the current instance of time
        OffsetDateTime date = OffsetDateTime.now(); 
        // printing the current date and time
        System.out.println(" The current date and time is: " + date);
        // creating another object to the Instant class to add time
        // adding 40 days to the current date and time using plus() method
        OffsetDateTime date1 = date.plusDays(40);  
        // printing date and time after adding 40 days
        System.out.println(" The date and time after adding 40 days to the current date and time is: " + date1);
    }
}

Output:

Add Time in Java

5. Apache commons:

The DateUtils class from the Apache Commons Lang library uncovered a static addHours() technique. The technique takes in a java.util.Date object alongside a sum we wish to add to it, the worth of which could be either sure or negative. The most recent variant of Apache Commons Lang is accessible at Maven Central.

Example:

// program to print the current date and time and add time to the current date and time using apache commons
import java.time.OffsetDateTime;  
import java.time.*;
import java.util.*;
import java.lang.*;
import org.apache.commons.lang3.time.DateUtils;
// importing the required packages and classes
class HelloWorld {
public static void main(String[] args) {
       System.out.println("Hello, World!");
       int add = 5; // initializing the integer literal
       // creating the object to the Date class and calling the getInstance(), getTime() method of Calendar class
      Date currentTime = Calendar.getInstance().getTime();
       System.out.println("Before Adding the time is : " + currentTime);
       // adding time to the current time
       targetTime = DateUtils.addMinutes(currentTime, add); // add minute
       // printing the time after adding 5 minutes
System.out.println("After adding 5 minutes to the current time is : " + currentTime);
    }
}

Output:

Add Time in Java

6. JODA time:

JODA Time is a choice as opposed to the Java 8 DateTime API and gives its own DateTime executions. The majority of its DateTime-related classes uncover plusHours() and minusHours() procedures to help us add or deduct a given number of hours from a DateTime object.

JODA-Time is an API made by joda.org which offers better classes and productive strategies to deal with dates and time than classes from java.util bundle like Calendar, Gregorian Calendar, Date, and so forth. This API is remembered for Java 8.0 with the java.time bundle.

Basic features of JODA time:

  • It utilizes simple field accessors like getYear(), getDayOfWeek(), getDayofYear().
  • It upholds 7 Calendar Systems like Buddhist, Coptic, Ethiopic, Gregorian, GregorianJulian, Islamic, and Julian.
  • There is a Provision to make our own Calendar framework.
  • It provides a rich Set of Methods for date and Time estimations.
  • It involves an information base for time regions. This data set is refreshed a few times physically in a year.
  • Its Methods execute quicker contrasted with before techniques for java 7.0; accordingly, it gives better execution.
  • Its Objects are changeless. Along these lines, they are string safe.

Related Topics

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.