Java LocalDate ofYearDay Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use the Java LocalDate ofYearDay() method to get a date from the specified year and number of days. You will learn about the syntax, parameters, and return type of the method, as well as see examples of how to use it in Java code.

Create a Java File

Create a new Java file in the ~/project directory called DateDemo.java by running the following command in the terminal:

touch ~/project/DateDemo.java

Import LocalDate Class

Add the code block below to your DateDemo.java file to import the LocalDate class.

import java.time.LocalDate;

Use ofYearDay() method

To use the ofYearDay() method, call it on the LocalDate class followed by the year and day-of-year parameters. Store the result in a LocalDate variable.

LocalDate localDate = LocalDate.ofYearDay(year, dayOfYear);

Provide Year and Day of Year

In the main() method of your DateDemo.java file, provide year and day of year for which you want to get the date.

int year = 2015;
int dayOfYear = 100;

Print the Result

Print the result using System.out.println().

System.out.println(localDate);

Your DateDemo.java file should now look like this:

import java.time.LocalDate;

public class DateDemo {

    public static void main(String[] args) {
        int year = 2015;
        int dayOfYear = 100;
        LocalDate localDate = LocalDate.ofYearDay(year, dayOfYear);
        System.out.println(localDate);
    }
}

Compile and Run the Java File

Compile your DateDemo.java file by running the following command in the terminal:

javac ~/project/DateDemo.java

Then, run your program with the following command:

java DateDemo

You should see the following output in the terminal:

2015-04-10

Experiment with Different Dates

Experiment with different years and day of years by modifying the year and dayOfYear variables. Run your program to see the results.

int year = 2021;
int dayOfYear = 365;

Handle Invalid Inputs

Remember that the day-of-year must be valid for the year, otherwise an exception will be thrown.

LocalDate localDate = LocalDate.ofYearDay(year, dayOfYear);

Play with the onDayOfYear() Method

The onDayOfYear() method returns a date-time value with the specified year and day-of-year. Try using it instead of ofYearDay().

LocalDate localDate = LocalDate.now().withDayOfYear(dayOfYear).withYear(year);

Summary

In this lab, you learned how to use the Java LocalDate ofYearDay() method to get a date from the specified year and number of days. You also learned how to handle invalid inputs, and how to use the onDayOfYear() method instead. By completing this lab you now have the knowledge needed to work with LocalDate objects in Java.

Other Java Tutorials you may like