在本文中,我們將了解如何顯示目前日期和時間。 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中文網其他相關文章!