如何在 Java 中正確使用 printf() 進行格式化?


printf() 方法用於列印格式化字串,它接受一個表示格式字串的字串和一個表示要包含在結果字串中的元素的物件陣列。如果引數數量超過格式字串中字元的數量,則會忽略多餘的物件。

下表列出了 Java printf() 方法用於格式化時間的各種格式字元及其描述:

格式字元描述
'H'
相應的引數格式化為一天中的小時(00-24)。
'I'
相應的引數格式化為一天中的小時(01-12)。
'k'
相應的引數格式化為一天中的小時(0-24)。
'l'
相應的引數格式化為一天中的小時(1-12)。
'M'
相應的引數格式化為小時的分鐘(00-59)。
'S'
相應的引數格式化為分鐘的秒數(00-60)。
'L'
相應的引數格式化為毫秒(000-999)。
'N'
相應的引數格式化為納秒(000000000-999999999)。
'p'
相應的引數格式化為下午或上午。
'z'
相應的引數格式化為時區。
'Z'
相應的引數格式化為表示時區的字串。
's'
相應的引數格式化為自紀元以來的秒數。
'Q'
相應的引數格式化為自紀元以來的毫秒數。

示例

以下示例演示瞭如何使用 printf() 方法格式化日期值。

線上演示

import java.util.Date;
public class Example {
   public static void main(String args[]) {  
      //creating the date class
      Date obj = new Date();
      System.out.printf("%tT%n", obj);
      System.out.printf("Hours: %tH%n", obj);
      System.out.printf("Minutes: %tM%n", obj);
      System.out.printf("Seconds: %tS%n", obj);
   }
}

輸出

15:50:28
Hours: 15
Minutes: 50
Seconds: 28

示例

以下示例演示瞭如何使用 Java printf() 方法列印 12 小時和 24 小時的時鐘。

線上演示

import java.util.Date;
public class Example {
   public static void main(String args[]) {  
      //creating the date class
      Date obj = new Date();
      System.out.printf("%tT%n", obj);
      System.out.printf("Time 12 hours: %tI:%tM %tp %n", obj, obj, obj); System.out.printf("Time 24 hours: %tH: hours %tM: minutes %tS: seconds%n", obj, obj, obj);
   }
}

輸出

11:38:08
Time 12 hours: 11:38 am
Time 24 hours: 11: hours 38: minutes 08: seconds

如果觀察上面的示例,我們使用相同的 date 物件列印各種值,我們可以使用索引引用 1$ 來避免使用多個引數,如下所示:

示例

線上演示

import java.util.Date;
public class Example {
   public static void main(String args[]) {  
      //creating the date class
      Date obj = new Date();
      System.out.printf("%tT%n", obj);
      System.out.printf("Time 12 hours: %tI:%1$tM %1$tp %n", obj);
      System.out.printf("Time 24 hours: %1$tH: hours %1$tM: minutes %1$tS: seconds%n", obj);
   }
}

輸出

11:47:13
Time 12 hours: 11:47 am
Time 24 hours: 11: hours 47: minutes 13: seconds

更新於: 2021-02-06

234 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告