How to retrieve dates for one year in Java?

In Java, you can use Java’s date and time classes (such as LocalDate and LocalDateTime) to retrieve dates for a year. Below is a sample code demonstrating how to get dates for a year and print them out:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        int year = 2021;

        LocalDate startDate = LocalDate.of(year, 1, 1);
        LocalDate endDate = LocalDate.of(year, 12, 31);

        while (!startDate.isAfter(endDate)) {
            System.out.println(startDate);
            startDate = startDate.plusDays(1);
        }
    }
}

The above code first defines a variable year for the year. Then, it uses the LocalDate.of() method to create startDate and endDate, representing the start and end dates of the year. A while loop is then used to iterate through the dates of the year, incrementing startDate by one day at a time using the plusDays() method, and printing out each date using System.out.println().

bannerAds