21xrx.com
2025-06-18 00:00:36 Wednesday
登录
文章检索 我的文章 写文章
Java程序教程:如何显示当前日期和时间
2023-06-12 10:47:02 深夜i     62     0
Java 日期 时间 LocalDateTime DateTimeFormatter

Java是一门跨平台的面向对象编程语言,它被广泛应用于Web开发、移动应用程序、桌面应用程序等领域。在Java中,获取并显示当前日期和时间是一项非常基本的操作。本文将介绍如何使用Java程序来获取和显示当前日期和时间。

首先,我们需要使用Java内置的日期时间类来获取当前日期和时间。Java内置的日期时间类库包括java.util.Date、java.util.Calendar和java.time包中的各种类。这里我们使用java.time包的LocalDateTime类来获取当前日期和时间:

import java.time.LocalDateTime;
public class GetDateAndTime {
  public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("Current Date and Time is: " + now);
  }
}

运行程序,将会显示当前日期和时间:

Current Date and Time is: 2021-09-10T14:35:02.784188

在上面的代码中,我们使用了LocalDateTime.now()方法来获取当前日期和时间。然后使用System.out.println()方法将其输出到控制台上。

除了显示当前日期和时间,我们还可以使用LocalDateTime类来格式化日期和时间的输出。例如,我们可以使用DateTimeFormatter类将日期和时间格式化为指定的格式:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatDateAndTime {
  public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formattedDateTime = now.format(formatter);
    System.out.println("Formatted Date and Time is: " + formattedDateTime);
  }
}

运行程序,将会以指定格式显示当前日期和时间:

Formatted Date and Time is: 2021-09-10 14:39:04

在上面的代码中,我们使用了DateTimeFormatter类和ofPattern()方法来指定日期和时间的输出格式。然后,使用LocalDateTime.format()方法将其格式化为指定的格式,并使用System.out.println()方法将其输出到控制台上。

  
  

评论区