Thursday 15 March 2018

How to subtract year using minus methods of Year Class | Java 8 Date and Time


Click here to watch on Youtube: 
https://www.youtube.com/watch?v=dW8O0-GjV-U&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:
         *
         * yearsToSubtract - the years to subtract, may be negative
         *
         * Returns:
         *
         * a Year based on this year with the year subtracted, not null
         */

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

}

Output

year1 = 2017
year2 = 2015

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:
         *
         * amountToSubtract - the amount of the unit to subtract from
         * the result, may be negative
         *
         * unit - the unit of the amount to subtract, not null
         *
         * Returns:
         *
         * a Year based on this year with the specified amount
         * subtracted, not null
         */

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

}

Output

year1 = 2017
year2 = 2012

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:
         *
         * amountToSubtract - the amount to subtract, not null
         *
         * Returns:
         *
         * a Year based on this year with the subtraction made, not
         * null
         */

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

}

Output

year1 = 2017
period = P9Y
year2 = 2008

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

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

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