在本文中,我们将了解如何显示当前日期和时间。 Java没有内置的Date类,但是我们可以导入java.time包来使用日期和时间API。该包包含许多日期和时间类。
下面是相同的演示 -
假设我们的输入是 -
Run the program
期望的输出是 -
The current date and time is: 2022/03/17 23:43:17
Step 1 - START Step 2 - Declare an object of LocalDateTime namely date. Step 3 - Define the values. Step 4 - Define a date time format using DateTimeFormatter objects Step 5 - Display the date and time using a specific formats Step 6 - Stop
这里,我们将所有操作绑定到“main”函数下。
import java.time.format.DateTimeFormatter; import java.time.LocalDateTime; public class Demo { public static void main(String[] args) { System.out.println("The required packages have been imported"); System.out.println("A LocalDateTime object has been defined"); DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("\nThe current date and time is: " +date_time.format(now)); } }
The required packages have been imported A LocalDateTime object has been defined The current date and time is: 2022/03/17 23:43:17
在这里,我们将操作封装到展示面向对象编程的函数中。
import java.time.format.DateTimeFormatter; import java.time.LocalDateTime; public class Demo { static void Date_time(DateTimeFormatter date_time){ LocalDateTime now = LocalDateTime.now(); System.out.println("\nThe current date and time is: " +date_time.format(now)); } public static void main(String[] args) { System.out.println("The required packages have been imported"); System.out.println("A LocalDateTime object has been defined"); DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); Date_time(date_time); } }
The required packages have been imported A LocalDateTime object has been defined The current date and time is: 2022/03/29 08:55:28
以上是Java程序显示当前日期和时间的详细内容。更多信息请关注PHP中文网其他相关文章!