Java LocalDate ofEpochDay Method

JavaJavaBeginner
Practice Now

Introduction

Java LocalDate ofEpochDay() method is used to get a LocalDate from the epoch-day count. The epoch-day is a simple incrementing count of days from January 1st, 1970.

Importing the LocalDate class

Import the java.time.LocalDate class to your Java program.

import java.time.LocalDate;

Using the ofEpochDay() method

To use the ofEpochDay() method, simply call it on the LocalDate class and pass it the epoch-day count. The method will return a new LocalDate instance based on the epoch-day count.

LocalDate date = LocalDate.ofEpochDay(10);

Getting a date 10 days ahead

Let's take an example to get a date 10 days ahead by using ofEpochDay() method. Here, we passed 10 days to the method and get a new LocalDate instance.

public class LocalDateofEpochDay {
    public static void main(String[] args) {
        // get a date 10 days ahead
        LocalDate date = LocalDate.ofEpochDay(10);
        System.out.println(date); // output: 1970-01-11
    }
}

To run the code, compile the file using the following command:

javac LocalDateofEpochDay.java

Then run the compiled class file using the following command:

java LocalDateofEpochDay

Getting a date ahead of 1 year

Here, we are getting a date ahead of 1 year by adding 365 epoch days.

public class LocalDateofEpochDay {
    public static void main(String[] args) {
        // get a date ahead of 1 year
        LocalDate date = LocalDate.ofEpochDay(365);
        System.out.println(date); // output: 1971-01-01
    }
}

To run the code, compile the file using the following command:

javac LocalDateofEpochDay.java

Then run the compiled class file using the following command:

java LocalDateofEpochDay

Summary

In this lab, we learned about the Java LocalDate ofEpochDay() method. We saw how to use this method to get a LocalDate from the epoch-day count. We created two examples to see how adding an epoch day calculates the correct date.

Other Java Tutorials you may like