如何在 Java 中使用 printf() 方法格式化時間?


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

下表列出了使用 printf() 方法列印日期的各種格式字元及其描述:

格式字元描述
'B'
相應的引數格式化為完整月份名稱。
'b'
相應的引數格式化為縮寫月份名稱。
'h'
相應的引數格式化為縮寫月份名稱。
'A'
相應的引數格式化為星期幾的名稱(完整)。
'a'
相應的引數格式化為星期幾的名稱(縮寫)。
'C'
相應的引數格式化為年份(四位年份除以 100)。
'Y'
相應的引數格式化為年份(4 位數字)。
'y'
相應的引數格式化為年份(2 位數字)。
'j'
相應的引數格式化為一年中的第幾天(3 位數字)。
'm'
相應的引數格式化為月份(2 位數字)。
'd'
相應的引數格式化為一個月中的第幾天(帶 0 的 2 位數字)。
'e'
相應的引數格式化為一個月中的第幾天(2 位數字)。

示例

以下示例演示瞭如何使用 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("%tD%n", obj);
      System.out.printf("Date: %td%n", obj);
      System.out.printf("Month: %tm%n", obj);
      System.out.printf("Year: %ty%n", obj);
   }
}

輸出

11/10/20
Date: 10
Month: 11
Year: 20

示例

以下示例演示瞭如何使用 Java 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("%tD%n", obj);
      System.out.printf("Year: %tY%n", obj);
      System.out.printf("Day of the year: %tj%n", obj);
   }
}

輸出

11/10/20
Year: 2020
Day of the year: 315

示例

以下示例演示瞭如何使用 Java 的 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("Date: %tD%n", obj);
      System.out.printf("Month (full): %tB%n", obj);
      System.out.printf("Month (abbrevation): %tb%n", obj);
      System.out.printf("Day (full): %tA%n", obj);
      System.out.printf("Day (abbrevation): %ta%n", obj);
   }
}

輸出

Date: 11/10/20
Month (full): November
Month (abbrevation): Nov
Day (full): Tuesday
Day (abbrevation): Tue

更新於: 2021 年 2 月 6 日

160 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告