Tuesday 3 April 2018

How to add days, hours etc using plus methods of Duration class | Java 8 Date and Time


Click here to watch on Youtube:
https://www.youtube.com/watch?v=w5LXa2LMf7c&list=UUhwKlOVR041tngjerWxVccw

DurationDemo1.java

import java.time.Duration;

public class DurationDemo1
{
    public static void main(String[] args)
    {
        Duration duration = Duration.ofDays(1);
        System.out.println("duration     = "+duration);

        duration = duration.plusDays(1);
        System.out.println("Plus 1 day   = "+duration);
       
        duration = duration.plusHours(2);
        System.out.println("Plus 2 hours = "+duration);
       
        duration = duration.plusMinutes(50);
        System.out.println("Plus 50 mins = "+duration);
       
        duration = duration.plusSeconds(40);
        System.out.println("Plus 40 secs = "+duration);
       
        duration = duration.plusMillis(10);
        System.out.println("Plus 10 Millis = "+duration);
       
        duration = duration.plusNanos(70000);
        System.out.println("Plus 70000 Nanos = "+duration);

    }

}

Output

duration     = PT24H
Plus 1 day   = PT48H
Plus 2 hours = PT50H
Plus 50 mins = PT50H50M
Plus 40 secs = PT50H50M40S
Plus 10 Millis = PT50H50M40.01S
Plus 70000 Nanos = PT50H50M40.01007S

DurationDemo2.java

import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class DurationDemo2
{
    public static void main(String[] args)
    {
        Duration duration = Duration.ofDays(1);
        System.out.println("duration         = " + duration);

        /*
         * Parameters:
         *
         * amountToAdd - the amount to add, measured in terms of the
         * unit, positive or negative
         *
         * unit - the unit that the amount is measured in, must have
         * an exact duration, not null
         *
         * Returns:
         *
         * a Duration based on this duration with the specified
         * duration added, not null
         */

        duration = duration.plus(1, ChronoUnit.DAYS);
        System.out.println("Plus 1 days      = " + duration);

        duration = duration.plus(20, ChronoUnit.MINUTES);
        System.out.println("Plus 20 minutes  = " + duration);

    }

}

Output

duration         = PT24H
Plus 1 days      = PT48H
Plus 20 minutes  = PT48H20M

Click the below link to download the code:
https://sites.google.com/site/ramj2eev2/java_basics/DurationDemo_plus.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava_2018/DurationDemo_plus

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/c7899e666996cf29a48ef15f0030404863025004/BasicJava_2018/DurationDemo_plus/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment