学习获取当前本地日期

JavaBeginner
立即练习

介绍

在本实验中,你将学习 Java 的 LocalDate now() 方法,该方法用于获取当前的本地日期。它根据默认的系统区域设置返回系统日期。

导入所需的包

java.time 包中包含我们需要在程序中使用的 LocalDate 类。我们还需要导入 java.time.format.DateTimeFormatter 类来格式化 LocalDate 的输出。

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

定义 main 方法

让我们在程序中定义 main() 方法。

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

获取当前本地日期

为了使用 now() 方法获取当前本地日期,可以创建一个 LocalDate 对象,如下所示。

LocalDate currentDate = LocalDate.now();

打印当前日期

要使用 now() 方法打印当前日期,可以打印上一步中创建的 currentDate 对象。

System.out.println(currentDate);

格式化当前日期

如果我们想要格式化 now() 方法的输出,可以创建一个带有指定格式的 DateTimeFormatter 对象,并使用 format() 方法将格式应用到 currentDate 对象上。

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

编译并运行程序

要编译程序,打开终端并导航到 ~/project 目录。然后,输入以下命令:

javac LocalDateDemo.java

编译成功后,使用以下命令运行程序:

java LocalDateDemo

输出

程序将输出默认格式的当前日期以及指定格式的格式化日期。

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

总结

在本实验中,你学习了如何使用 Java 的 LocalDate now() 方法获取当前的本地日期。你还学习了如何使用 Java 中的 DateTimeFormatter 类格式化 now() 方法的输出。