How to make Java program to add some hours to the current time

In this tutorial, we will learn how to add some hours to the current time in Java. This program will help you to develop more knowledge about some parts of Java. Before starting further we need to understand about java.time.* which is basically packaged in Java which contains a collection of classes.

Some important classes inside this package are- Clock, Duration, Instant, LocalDate, LocalDateTime, LocalTime, Period, Year, MonthDay, OffsetDateTime, OffsetTime, YearMonth, ZonedDateTime, Zoneld, ZoneOffset .

Add some hours to the current time in Java

Steps followed on the program:
1. The step is to import all the classes inside the java.time package.

import java.time.*;

2. The second step is to create an object of the LocalTime class which is time without a time-zone in the ISO-8601 calendar system, such as11:10:20.

LocalTime time = LocalTime.now();

where time is the reference variable and LocalTime.now() is the method that obtains the current time from the system clock in the default time-zone.
3. The third step is to add some hours in the current time, where plusHours(long hours_to_be_added) is a method that returns a copy of this LocalTime with the specified number of hours added.

LocalTime newtime = time.plusHours(3)import java.time.*;

4. The final step is to print the new time after added hours.

System.out.println("Time after 3 hours : " + newTime);

COMPLETE CODE-

import java.time.*;
public class add__time {
   public static void main(String[] args)
    {
     //Creating a LocalTime object
      LocalTime time = LocalTime.now(); 
      // adding three hours
      LocalTime newtime = time.plusHours(3);
      System.out.println("Time after 3 hours : " + newTime);
        }
}
OUTPUT:

Time after 3 hours  :  16:38:29.089

We hope you can now add hours to current time in Java with the help of this tutorial.

Read a similar program: Get The Current Time In Java 
 This program will help you understand some important classes in Java packages.

Leave a Reply

Your email address will not be published. Required fields are marked *