How to add hours and minutes to Java Instant


To add hours or minutes to the Java Instant Class object we can make use of the plus methods from the Instant class.

Example:
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class JavaInstantClassExample {

    public static void main(String[] args) {

        int hoursToAdd = 4;
        int minutesToAdd = 30;
        Instant currentTimeStampInUTC = Instant.now();
        System.out.println("Current Time: "+currentTimeStampInUTC);

        System.out.println("Adding 4 hours and 30 minutes to current time");
        Instant laterTime = currentTimeStampInUTC.plus(hoursToAdd,ChronoUnit.HOURS)
                                             .plus(minutesToAdd,ChronoUnit.MINUTES);
        System.out.println("Later Time: "+laterTime);
    }
}
Output:
Current Time: 2022-05-13T18:37:55.991272Z
Adding 4 hours and 30 minutes to current time
Later Time: 2022-05-13T23:07:55.991272Z
Java Instant class add hours and minutes

Top Hashtags:

Advertisements

Advertisements




Advertisements