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.
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.
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;
Let's define the main()
method in the program.
public class LocalDateDemo {
public static void main(String[] args){
// Code goes here
}
}
In order to get the current local date using now()
method, create a LocalDate
object as shown below.
LocalDate currentDate = LocalDate.now();
To print the current date using now()
method, we can print the currentDate
object created in the previous step.
System.out.println(currentDate);
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);
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
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
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.