Introduction
In this lab, we will learn how to use the lengthOfYear()
method of the LocalDate
class in Java. This method returns the length of a year in days. We will write Java code to demonstrate the use of this method.
In this lab, we will learn how to use the lengthOfYear()
method of the LocalDate
class in Java. This method returns the length of a year in days. We will write Java code to demonstrate the use of this method.
Create a Java file named LocalDateDemo.java
in the ~/project
directory using the following command:
touch ~/project/LocalDateDemo.java
In the LocalDateDemo.java
file, we need to import the LocalDate
class. Add the following line at the beginning of the file:
import java.time.LocalDate;
In the main
method of the LocalDateDemo
class, create a LocalDate
object for a date of your choice using the of
method. For example:
LocalDate date = LocalDate.of(2022, 1, 1); // January 1st, 2022
Call the lengthOfYear()
method on the LocalDate
object created in the previous step to get the length of the year. For example:
int length = date.lengthOfYear();
Print the value of the length
variable using the System.out.println()
method. For example:
System.out.println("Length of year: " + length);
Save the LocalDateDemo.java
file and compile it using the following command:
javac LocalDateDemo.java
Run the code using the following command:
java LocalDateDemo
You should see the length of the year printed on the console.
You can also use the LocalDate.now()
method to create a LocalDate
object that represents the current date. For example:
LocalDate currentDate = LocalDate.now();
Save the LocalDateDemo.java
file and compile it using the following command:
javac LocalDateDemo.java
Run the code using the following command:
java LocalDateDemo
You should see the length of the current year printed on the console.
In this lab, we have learned how to use the lengthOfYear()
method of the LocalDate
class in Java to get the length of a year in days. We created a LocalDate
object for a specific date, called the lengthOfYear()
method on it, and printed the result to the console. We also used the LocalDate.now()
method to create a LocalDate
object that represents the current date.