Java程式:AM-PM格式的時間格式化


時間格式化 是將日期和時間值轉換為具有特定格式的人類可讀字串的過程。生成的字串描述了日期/時間值應如何表示(例如平面檔案或人類可讀輸出)。在本文中,我們將瞭解如何以AM-PM格式格式化時間。

在12小時制中,使用AM-PM格式來定義時間。這裡,AM代表Ante meridiem(上午),而PM代表Post meridiem(下午)。

示例場景

Input: current_date = Thu Mar 17 16:04:31 IST 2024
Output: Current Time in AM/PM format is = 04.04 pm

以AM-PM格式格式化時間的方法

要以AM-PM格式格式化時間,我們可以使用以下方法:

  • 使用SimpleDateFormat類
  • 使用使用者定義函式

使用SimpleDateFormat類

Java中,SimpleDateFormat類DateFormat類的子類。它提供多種方法來解析和格式化日期/時間。它允許我們為格式化目的選擇任何使用者定義的模式。

示例

在這個例子中,我們將使用SimpleDateFormat類的format()方法以AM-PM格式化時間。

import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Date current_date = new Date();
      System.out.println("The current date is: " + current_date);
      SimpleDateFormat formatTime = new SimpleDateFormat("hh.mm aa");
      String result_time = formatTime.format(current_date);
      System.out.println("\nThe current Time in AM/PM format is : " + result_time);
   }
}

執行上述程式碼後,將顯示以下輸出:

The required packages have been imported
The current date is: Thu Mar 17 16:04:31 IST 2024

The current Time in AM/PM format is : 04.04 pm

使用使用者定義函式

使用者定義函式中,我們將傳遞當前日期並使用format()方法以AM-PM格式格式化日期和時間值。程式設計師建立的用於執行特定任務的程式碼塊稱為使用者定義函式。

示例

在這裡,我們定義了一個函式來以AM-PM格式格式化日期/時間。

import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo {
   static void format_time(Date current_date){
      SimpleDateFormat formatTime = new SimpleDateFormat("hh.mm aa");
      String result_time = formatTime.format( current_date);
      System.out.println("\nThe current Time in AM/PM format is : " + result_time);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Date current_date = new Date();
      System.out.println("The current date is: " + current_date);
      format_time(current_date);
   }
}

執行此程式碼後,將產生以下結果:

The required packages have been imported
The current date is: Thu Mar 17 16:04:31 IST 2024
The current Time in AM/PM format is : 04.04 pm

更新於:2024年8月1日

瀏覽量:1K+

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.