×

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

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.