×

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 String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.