Learn Current Local Date

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn about Java LocalDate now() method which is used to get the current local date. It returns the default system date based on the locale.

Import required packages

The java.time package contains the LocalDate class, which we need to use in our program. We also need to import java.time.format.DateTimeFormatter class to format the LocalDate output.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

Define the main method

Let's define the main() method in the program.

public class LocalDateDemo {
    public static void main(String[] args){
        // Code goes here
    }
}

Get current local date

In order to get the current local date using now() method, create a LocalDate object as shown below.

LocalDate currentDate = LocalDate.now();

Print the current date

To print the current date using now() method, we can print the currentDate object created in the previous step.

System.out.println(currentDate);

Format the current date

If we want to format the output of now() method, we can create a DateTimeFormatter object with the required format and use the format() method to apply the format to the currentDate object.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = currentDate.format(formatter);
System.out.println("Formatted date: " + formattedDate);

Compile and run the program

To compile the program, open the terminal and navigate to the ~/project directory. Then, enter the following command:

javac LocalDateDemo.java

After successful compilation, run the program with the following command:

java LocalDateDemo

Output

The program will output the current date in the default format and the formatted date in the desired format.

2020-11-13
Formatted date: 13/11/2020

Summary

In this lab, you have learned how to use Java LocalDate now() method to get the current local date. You also learned how to format the output of the now() method using DateTimeFormatter class in Java.

Other Java Tutorials you may like