Monday, 2 April 2018

How to create duration object using ofNanos, ofSeconds methods of Duration class


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

DurationDemo1.java

import java.time.Duration;

public class DurationDemo1
{
    public static void main(String[] args)
    {
        /*
         * Parameters:
         *
         * nanos - the number of nanoseconds, positive or negative
         *
         * Returns:
         *
         * a Duration, not null
         */

        Duration duration1 = Duration.ofNanos(2000000);
        System.out.println("duration1 = "+duration1);
       
        /*
         * Parameters:
         *
         * seconds - the number of seconds, positive or negative
         *
         * Returns:
         *
         * a Duration, not null
         */

        Duration duration2 = Duration.ofSeconds(10);
        System.out.println("duration2 = "+duration2);
    }

}

Output

duration1 = PT0.002S
duration2 = PT10S

DurationDemo2.java

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

public class DurationDemo2
{
    public static void main(String[] args)
    {
        /*
         * Parameters:
         *
         * seconds - the number of seconds, positive or negative
         *
         * nanoAdjustment - the nanosecond adjustment to the number of
         * seconds, positive or negative
         *
         * Returns:
         *
         * a Duration, not null
         */

        Duration duration1 = Duration.ofSeconds(10, 909090);
        System.out.println("duration1 = " + duration1);

        /*
         * Parameters:
         *
         * amount - the amount of the duration, measured in terms of
         * the unit, positive or negative
         *
         * unit - the unit that the duration is measured in, must have
         * an exact duration, not null
         *
         * Returns:
         *
         * a Duration, not null
         */

        Duration duration2 = Duration.of(10, ChronoUnit.DAYS);
        System.out.println("duration2 = " + duration2);
    }

}

Output

duration1 = PT10.00090909S
duration2 = PT240H

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/c7899e666996cf29a48ef15f0030404863025004/BasicJava_2018/DurationDemo_of_nanos_sec/?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