Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
java.time.Year Class in Java
Next article icon

java.time.Year Class in Java

Last Updated : 22 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The java.time.Year class represents a year in the ISO-8601 calendar system, such as 2021. Year is an immutable date-time object that represents a year. This class does not store or represent a month, day, time, or time-zone. The years represented by this class follow the proleptic numbering system that is as follows: 

The year 0 is preceded by year -1 and succeeded by the year 1.

Syntax: Class Declaration

public final class Year extends Object implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable

Now let us do discuss all the methods of this Year class which is shown below in a tabular format. Later on, we will be discussing them individually.

MethodDescription
adjustsIntro()Adjusts the specified temporal object to have this year.
atDay()Creates a local date with day number equal to the number in the Year class object
atMonth()Combine this year with a month to create a YearMonth 
atMonthDay()Combine this year with a month date to create a LocalDate 
compareTo()Compares the two-year objects.
equals()Checks if two-year objects are equal.
format()Formats the year using specified datetime formatter.
get()Gets the value of the specified field from this year.
getLong()Getting the value of a specified field from this year as a long 
getValue()Returns the integer value of the year.
hashCode()Returns the hashcode of the year object.
isAfter()Checks whether the year is after year1.
isBefore()Checks whether the year is before year1.
isLeap()Checks whether the year is a leap year or not.
isSupported()Checks if the specified temporal field is supported.
isValidMonthDay()Checks if the month-day is valid for this year
length()Returns the number of days in the year.
minus()Returns the copy of this year with the specified amount subtracted
minusYears()Subtracts a number of years from a year and returns a new Year object.
now()Gets current year and creates a Year object.
of()

"Creates Year object with year equal to the number.

0 is used for 0 AD whereas -1 is used for 1 BC."

parse()Obtains an instance of Year from a text string such as 2021.
plus()Returns a copy of this year with the specified number of years added.
plusYears()Adds num years to a year and returns a new Year object.
query()Queries this year using the specified query.
range()getting the range of valid values for the specified field. 
toString()Returns the current year as a string.
until()Calculates the amount of time until another year in terms of the specified unit.
with()Returns an adjusted copy of the year.

Let us discuss a few of the frequently used methods of this class in detail to get a better understanding so as to implement the rest of them too. Here we will be discussing our major methods namely as follows:

  1. atDay()
  2. hashCode()
  3.  isAfter()
  4. isBefore()
  5. isLeap()
  6. now()
  7. minus()

Method 1: atDay() method of Year class in Java combines the current year with a day-of-year passed as a parameter to it to create a LocalDate.

Syntax: 

public LocalDate atDay(int dayOfYear)

Parameter: This method accepts a single parameter day of the year. It is the day-of-year to use. It can take values from 1 to 365-366.

Return Value: It returns a Local Date formed by the current year and the date of the year passed as a parameter to the function.

Exception: This method throws a DateTimeException, if the day of year passed in the parameter is not valid, that is zero or less, 366 or greater or equal to 366 and the current year is not a leap year.

Method 2: hashCode() 

It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing-based collections like HashMap, HashSet, HashTable,etc. This method must be overridden in every class which overrides the equals() method.
Syntax:

public int hashCode()  // This method returns the hash code value  // for the object on which this method is invoked.

Method 3: 

The isAfter() method of Year class in Java is used to check if this current Year object is after the Year specified as a parameter to this method.

Syntax:

public boolean isAfter(Year otherYear)

Parameter: It accepts a single parameter another year with which the current Year object is to be compared.

Return Value: It returns a boolean True value if this Year object’s value is after the value of Year object specified as a parameter to the method, otherwise it returns False.

Method 4: 

The isBefore() method of Year class in Java is used to check if this current Year object is before the Year specified as parameter to this method.

Syntax:

public boolean isBefore(Year otherYear)

Parameter: It accepts a single parameter otherYear with which the current Year object is to be compared.

Return Value: It returns a boolean True value if this Year object’s value is before the value of Year object specified as a parameter to the method, otherwise it returns False.

Method 5:

The isLeap() method of Year class in Java is used to check if this Year object is a leap year or not according to the proleptic calendar system rules.

A year is a leap year if it has 366 days in it. According to the proleptic calendar system rules, a year is a Leap year if:

  • If it is divisible by 4.
  • It is not divisible by 100, but it can be divisible by 400.

Syntax:

public boolean isLeap()

Parameter: This method does not accept any parameter.

Return Value: It returns a boolean True value if this Year object’s value is a leap year according to the proleptic calendar system rules, otherwise it returns False.

Method 6:

The now() method of Year class in Java is used to return the current year from the system clock in the default time-zone.

Syntax:

public static Year now()  or, public static Year now(Clock clock)  or, public static Year now(ZoneId zone)

Parameter: The parameter is optional for this method as shown in the above syntax.

Return Value: It returns the current year from the system clock in the default time-zone if no parameter is specified otherwise it uses the specified clock and time zone to return the current year. It can never return a NULL value

Method 7: 

The minus() method of Year class is used to return a copy of this year after subtracting the specified amount of unit from this Year object.An exception is thrown, If the specified unit cannot be subtracted from Year. This instance is immutable and unaffected by this method call.

Syntax:

public Year minus(long amountToSubtract, TemporalUnit unit)

Parameters: This method accepts two parameters which are s follow:

  • amountToSubtract
    • This parameter represents the amount of the unit to subtract from the result.
  • unit
    • This parameter represents the unit of the amount to subtract.

Return Value: This method returns a Year based on this year with the specified amount subtracted.

Exception: This method throws the following Exceptions:

  • DateTimeException
    • This exception is thrown if the subtraction cannot be made.
  • UnsupportedTemporalTypeException
    • This exception is thrown if the unit is not supported.
  • ArithmeticException
    • This exception is thrown if numeric overflow occurs.

You can co-relate the same for the plus() method. By now we are over with discussing the methods. Now it's time to implement the same to demonstrate the Year class.

Implementation:

Example

Java
// Java Program to illustrate java.time.Year class import java.time.*;  // Importing all classes from // time package to get other functionalities import java.time.Year;  //  Class public class GFG {      // Main driver method     public static void main(String[] args)     {          // Object 1         // Creating an Year class object          // getting the current year each         // using the now() method         Year y = Year.now();          // Print and display the current year         System.out.println("Current year: " + y);          // Object 2         // Creating another Year class object Object         // Here year 2020 as passed as an argument         Year y1 = Year.of(2020);          // Object 3         // Creating another object of year class         // again passing year 2022 as an argument         Year y2 = Year.of(2022);          // Now, creating a LocalDate object and         // getting the local date at the day         // passed as an argument         // Custom input argument = 350         LocalDate l = y.atDay(350);          // Print the local date         System.out.println("Local date: " + l);          // Now, creating a YearMonth         // and retrieving month using atMonth() method         // by passing argument to the method         // Custom input argument- 6         YearMonth ym = y.atMonth(6);          // Print the year and the month         System.out.println("Year and month: " + ym);          // Printing number of days of current Year         System.out.println("Number of days: " + y.length());          // Checking if Year y         // is before Year y2         System.out.println("2021 is before 2022: "                            + y.isBefore(y2));         // check if Year y         // is after Year y1         System.out.println("2021 is after 2020: "                            + y.isAfter(y1));          // Now, printing hashcode of the year         // using the hashcode() method         System.out.println("Hashcode of the year: "                            + y.hashCode());          // Checking whether the year is leap year or not         System.out.println("2020 is leap year: "                            + y1.isLeap());          // Adding 150 years to the current year         System.out.println("2021 - 155 years: "                            + y.minusYears(155));         // Subtracting 150 years from the current year         System.out.println("2021 + 145 years: "                            + y.plusYears(145));     } } 

Output
Current year: 2021 Local date: 2021-12-16 Year and month: 2021-06 Number of days: 365 2021 is before 2022: true 2021 is after 2020: true Hashcode of the year: 2021 2020 is leap year: true 2021 - 155 years: 1866 2021 + 145 years: 2166


 


Next Article
java.time.Year Class in Java

M

mehulp1612
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Technical Scripter 2020
  • Java-time package
  • Java-Year
Practice Tags :
  • Java

Similar Reads

    java.time.YearMonth Class in Java
    Java YearMonth class provides the output of the format "year-month". This class is an immutable class which means that it defines objects which, once created, never change their value. Any field which will be derived from a year and month, like quarter-of-year, are often obtained. This class does no
    4 min read
    java.time.Period Class in Java
    The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days. The units which are supported for a period are YEARS, MONTHS, and days. Al
    5 min read
    java.time.OffsetDateTime Class in Java
    Java is the most popular programming language and widely used programming language. Java is used in all kind of application like mobile application, desktop application, web application. In this Java java.time.OffsetDate, Time class is imported which is an immutable representation of a date-time wit
    4 min read
    java.time.LocalDate Class in Java
    Java is the most popular programming language and widely used programming language. Java is used in all kind of application like as mobile application, desktop application, web application. In this Java java.time.LocalDate class is imported which represents to display the current date. java.time: It
    4 min read
    Year atDay() method in Java
    The atDay() method of Year class in Java combines the current year with a day-of-year passed as parameter to it to create a LocalDate. Syntax: public LocalDate atDay(int dayOfYear) Parameter: This method accepts a single parameter dayOfYear. It is the day-of-year to use. It can take values from 1 to
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences