Java程式顯示小時和分鐘,並顯示AM或PM
在本文中,我們將學習如何使用Java 中的Formatter和Calendar類來格式化日期和時間。Formatter類允許靈活的字串格式化,而Calendar類則用於檢索和操作日期和時間值。我們將使用這些類來顯示當前的小時、分鐘和AM/PM標記。
問題陳述
給定一個Calendar例項,編寫一個Java程式,使用Formatter類顯示當前的小時、分鐘和AM/PM標記。輸入
The program fetches the current date and time using the Calendar class.輸出
Current date and time: Mon Nov 26 07:41:35 UTC 2018Hour and Minute with AM/ PM: 7:41 AM Hour: 7 AM Minute: 41
使用AM/PM格式化當前時間的步驟
以下是使用AM/PM格式化當前時間的步驟
- 匯入必要的類:來自java.util包的Formatter和Calendar。
- 建立一個Formatter例項來格式化輸出。
- 使用Calendar.getInstance()獲取當前日期和時間。
- 在Formatter類中使用格式說明符列印小時、分鐘和AM/PM標記。
- 顯示格式化的輸出。
使用Formatter格式化日期和時間的Java程式
以下是使用Formatter格式化日期和時間的示例
import java.util.Calendar; import java.util.Formatter; public class Demo { public static void main(String args[]) { Formatter f = new Formatter(); Calendar c = Calendar.getInstance(); System.out.println("Current date and time: "+c.getTime()); f = new Formatter(); System.out.println(f.format("Hour and Minute with AM/ PM: %tl:%1$tM %1$Tp", c)); f = new Formatter(); System.out.println(f.format("Hour: %tl %1$Tp", c)); f = new Formatter(); System.out.println(f.format("Minute: %1$tM", c)); } }
輸出
Current date and time: Mon Nov 26 07:41:35 UTC 2018 Hour and Minute with AM/ PM: 7:41 AM Hour: 7 AM Minute: 41
程式碼解釋
在程式中,使用Calendar物件獲取當前日期和時間。Formatter類使用諸如%tl(12小時格式)、%tM(分鐘)和%Tp(AM/PM標記)之類的說明符來格式化輸出。格式化的輸出顯示當前的小時、分鐘和AM/PM標記。
廣告