×

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this date object as it is understood in the local time zone.

Since JDK version 1.1, Calendar.get has taken its position as the preferred method (Calendar.YEAR)

Syntax:

public int getYear() 

Parameters

None

Return

The year indicated by this date is returned by the getYear() method.

GetYear.java

import java.util.Date;  
public class GetYear {  
    public static void main(String[] args) {  
        Date d=new Date();  
        int year=d.getYear();  
        System.out.println("The year for the date object is : "+year);  
        System.out.println("***Add 1900 to the value of the year acquired from this date object to obtain the current year***");  
int currentYear=year+1900;  
        System.out.println("The Current year is: "+currentYear);  
        }  
}  

Output:

Get year from date in Java

How to Get the Current Year in Java Using Date and LocalDate Class

Java.util.Date the value returned by the getyear() function is deducted from 1900. However, Java long ago deprecated this approach. To do any Date and Time operations, we may instead utilize the LocalDate class included in the Java.time package.

Using the date.toInstant() method, which returns the time instant, we convert the date object to a LocalDate object. The system's default timezone is then specified by using atZone() after supplying the value of ZoneId.systemDefault() to the function Object() { [native code] } of atZone. Finally, we use the toLocalDate() function to change the instant value into a LocalDate.

Using the LocalDate object getLocalDate that we have now, we can obtain the year using getLocalDate.getYear().

GetYearProgram.java

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class GetYearProgram {
    public static void main(String[] args) {
        Date date = new Date();
        ZoneId timeZone = ZoneId.systemDefault();
        LocalDate getLocalDate = date.toInstant().atZone(timeZone).toLocalDate();
        System.out.println(getLocalDate.getYear());
    }
}

Output:

Get year from date in Java

Using Date and SimpleDataFormat to determine the current year

When the time is set to 00:00:00, Date returns the time and date. We use SimpleDateFormat to prepare the date to obtain the year. By passing in the format yyyy, we generate a SimpleDateFormat object. The date is sent as an argument when format() is used. getYearFormat.format(date)  gives back the outcome as a string, as shown in the output.

JavaGetYear.java

import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaGetYear {
    public static void main(String[] args) {
        Date date = new Date();


        SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy");
        String currentYear = getYearFormat.format(date);
        System.out.println(currentYear);
        
    }
}

Output:

Get year from date in Java

How to get the Current Year Using Date.getYear() and Calendar class

The final method uses the Calendar class, which is supposed to contain several Java.util.Date methods. We construct a Date object and obtain a calendar instance using calendar. getInstance().Then we call the function calendar.setTime() that sets the time on the Calendar using the date.

To obtain the year, we now call a calendar.get() function that returns the value of the field supplied as its argument. The Calendaer.YEAR year is provided to us as an integer.

DateGetYearJava.java

import java.util.Calendar;
import java.util.Date;
public class DateGetYearJava {
    public static void main(String[] args) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dateYear = calendar.get(Calendar.YEAR);
        System.out.println(dateYear);


    }
}

Output:

Get year from date in Java

java.time.LocalDate.getYear() Method Example

Explanation

The Java.time.LocalDate.getYear() approach obtains the year field.

Declaration

The Java.time.LocalDate.getYear() method declaration is as follows.

public int getYear()

Return Value

from MIN YEAR to MAX YEAR, the year

GetYearInJava.java

import java.time.LocalDate;
public class GetYearInJava {
   public static void main(String[] args) {   
      LocalDate date = LocalDate.parse("2022-02-03");
      System.out.println(date.getYear());  
   }
}

Output

Get year from date in Java

GetYear.java

// Java Program to Get Year From Date
// Using the LocalDate class
// Introducing Classes/Files
import java.time.LocalDate;
import java.time.Month;
import java.util.Date;
// Primary class
class GetYear {
// Method 1
// To get the year
public static void getYear(String date)
{
// Obtaining a LocalTime instance from a date
LocalDate currentDate = LocalDate.parse(date);
// Getting the year from the date
int year = currentDate.getYear();
// The year is printed.
System.out.println("Year: " + year);
}
// Method 2
// The primary driver method
public static void main(String args[])
{
// Setting a date
String date = "2022-10-21";
// Special Call
getYear(date);
}
}

Output:

Get year from date in Java

GetYearInJava.java

// Java Program to Get Year From Date
// using the calendar class
// Classes Importing/Files
import java.util.*;
// main class
class GetYearInJava {
// Driver Main Code
public static void main(String args[])
{
// Developing an object for a calendar
Calendar Cal
= new GregorianCalendar(
2022, 10, 21);
// Developing an object for a calendar
// object
int year = Cal.get(Calendar.YEAR);
// The year value is being printed
System.out.println("Year: " + year);
}
}

Output:

Get year from date in Java

Related Topics

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.