Java如何获取今天的日期和时间?

本示例向您展示如何使用JDK 8中引入的新的Date and Time API来获取当前日期和时间。要在此新API中获取今天的日期,您可以构造或的实例LocalDate,然后调用其方法。LocalTimeLocalDateTimetoString()

所有这些类都位于新java.time程序包下,并定义为最终类。因为其构造函数声明为私有构造函数,所以这意味着您无法使用其构造函数来创建新实例。但是这些类提供了一些静态工厂方法来获取其表示的值或创建新实例。例如,所有这些类都提供了now()一种返回当前日期,时间或日期和时间信息的方法。

让我们在TodayDateTime示例中查看完整的代码片段以进行演示。

package org.nhooo.example.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class TodayDateTime {
    public static void main(String[] args) {
        // 从系统时钟中获取当前日期
        // 默认时区。
        LocalDate currentDate = LocalDate.now();
        System.out.println("currentDate = " + currentDate);

        // 从系统时钟中获取当前时间
        // 默认时区。
        LocalTime currentTime = LocalTime.now();
        System.out.println("currentTime = " + currentTime);

        // 从系统时钟获取当前日期时间
        // 在默认时区。
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("currentDateTime = " + currentDateTime);
    }
}

运行该程序将为您提供以下结果:

currentDate = 2014-09-05
currentTime = 16:39:24.819
currentDateTime = 2014-09-05T16:39:24.820