Thursday 15 March 2018

How to add year using plus methods of Year Class | Java 8 Date and Time


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

YearDemo1.java

import java.time.Year;

public class YearDemo1
{

    public static void main(String[] args)
    {
        Year year1 = Year.of(2017);
        System.out.println("year1 = " + year1);

        /*
         * Parameters:
         *
         * yearsToAdd - the years to add, may be negative
         *
         * Returns:
         *
         * a Year based on this year with the years added, not null
         */

        Year year2 = year1.plusYears(2);
        System.out.println("year2 = " + year2);
    }

}

Output

year1 = 2017
year2 = 2019

YearDemo2.java

import java.time.Year;
import java.time.temporal.ChronoUnit;

public class YearDemo2
{

    public static void main(String[] args)
    {
        Year year1 = Year.of(2017);
        System.out.println("year1 = " + year1);

        /*
         * Parameters:
         *
         * amountToAdd - the amount of the unit to add to the result,
         * may be negative
         *
         * unit - the unit of the amount to add, not null
         *
         * Returns:
         *
         * a Year based on this year with the specified amount added,
         * not null
         */

        Year year2 = year1.plus(5, ChronoUnit.YEARS);
        System.out.println("year2 = " + year2);
    }

}

Output

year1 = 2017
year2 = 2022

YearDemo3.java

import java.time.Period;
import java.time.Year;

public class YearDemo3
{

    public static void main(String[] args)
    {
        Year year1 = Year.of(2017);
        System.out.println("year1 = " + year1);

        Period period = Period.ofYears(9);
        System.out.println("period = " + period);

        /*
         * Parameters:
         *
         * amountToAdd - the amount to add, not null
         *
         * Returns:
         *
         * a Year based on this year with the addition made, not null
         */

        Year year2 = year1.plus(period);
        System.out.println("year2 = " + year2);
    }

}

Output

year1 = 2017
period = P9Y
year2 = 2026

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/8e3f14caa10b52912934997a22df069c728f47b4/BasicJava_2018/YearDemo_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