How to Get Year from a Date in Java


We will cover examples for both older Java Date class as well as the preferred new Java Date Time API LocalDate class.


Example: Java Date Class (before Java 8)

package org.code2care.examples;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Example {

    public static void main(String... args) {
        Date date = new Date();
        SimpleDateFormat sdfForYear = new SimpleDateFormat("yyyy");
        String year = sdfForYear.format(date);
        System.out.println("Year from date: " + date + " is " + year);
    }
}
Output:

Year from date: Wed Oct 18 05:48:50 CDR 2023 is 2023


Example: Using LocalDate (Java 8 or above)

package org.code2care.examples;

import java.time.LocalDate;

public class Example {

    public static void main(String... args) {

        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        System.out.println("Year from date: " + localDate + " is " + year);
    }
}
Output:

Year from date: 2023-10-18 is 2023

Java Example - Get Year from Date

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap