使用 Java 中的 Formatter 僅顯示小時和分鐘


首先,建立一個 Formatter 和一個 Calendar 物件。

Formatter f = new Formatter();
Calendar c = Calendar.getInstance();

要使用 Formatter 類顯示小時,請使用“l”轉換字元 -

f = new Formatter();
System.out.println(f.format("Hour: %tl", c));

要使用 Formatter 類顯示分鐘,使用“M”轉換字元 -

f = new Formatter();
System.out.println(f.format("Minute: %1$tM", c));

以下是一個示例 -

示例

 即時演示

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", c));
      f = new Formatter();
      System.out.println(f.format("Minute: %1$tM", c));
   }
}

輸出

Current date and time: Mon Nov 26 07:35:43 UTC 2018
Hour and Minute with AM/ PM: 7:35 AM
Hour: 7
Minute: 35

更新於: 30-Jul-2019

182 次瀏覽

開啟你的 職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.