java格式化輸出 printf 例子

 1 import java.util.Date;
 2  
 3  
 4  
 5 public class Printf {
 6  
 7 public static void main(String[] args) {
 8  
 9 // %s表示輸出字符串,也就是將後面的字符串替換模式中的%s
10 System.out.printf("%s", new Integer(1212));
11 // %n表示換行
12 System.out.printf("%s%n", "end line");
13 // 還能夠支持多個參數
14 System.out.printf("%s = %s%n", "Name", "Zhangsan");
15 // %S將字符串以大寫形式輸出
16 System.out.printf("%S = %s%n", "Name", "Zhangsan");
17 // 支持多個參數時,能夠在%s之間插入變量編號,1$表示第一個字符串,3$表示第3個字符串
18 System.out.printf("%1$s = %3$s %2$s%n", "Name", "san", "Zhang");
19  
20  
21 System.out.printf("true = %b; false = ", true);
22 System.out.printf("%b%n", false);
23  
24  
25 Integer iObj = 342;
26 // %d表示將整數格式化爲10進制整數
27 System.out.printf("%d; %d; %d%n", -500, 2343L, iObj);
28 // %o表示將整數格式化爲8進制整數
29 System.out.printf("%o; %o; %o%n", -500, 2343L, iObj);
30 // %x表示將整數格式化爲16進制整數
31 System.out.printf("%x; %x; %x%n", -500, 2343L, iObj);
32 // %X表示將整數格式化爲16進制整數,而且字母變成大寫形式
33 System.out.printf("%X; %X; %X%n", -500, 2343L, iObj);
34  
35  
36 Double dObj = 45.6d;
37 // %e表示以科學技術法輸出浮點數
38 System.out.printf("%e; %e; %e%n", -756.403f, 7464.232641d, dObj);
39 // %E表示以科學技術法輸出浮點數,而且爲大寫形式
40 System.out.printf("%E; %E; %E%n", -756.403f, 7464.232641d, dObj);
41 // %f表示以十進制格式化輸出浮點數
42 System.out.printf("%f; %f; %f%n", -756.403f, 7464.232641d, dObj);
43 // 還能夠限制小數點後的位數
44 System.out.printf("%.1f; %.3f; %f%n", -756.403f, 7464.232641d, dObj);
45  
46  
47 // %t表示格式化日期時間類型,%T是時間日期的大寫形式,在%t以後用特定的字母表示不一樣的輸出格式
48 Date date = new Date();
49 long dataL = date.getTime();
50 // 格式化年月日
51 // %t以後用y表示輸出日期的年份(2位數的年,如99)
52 // %t以後用m表示輸出日期的月份,%t以後用d表示輸出日期的日號
53 System.out.printf("%1$ty-%1$tm-%1$td; %2$ty-%2$tm-%2$td%n", date, dataL);
54 // %t以後用Y表示輸出日期的年份(4位數的年),
55 // %t以後用B表示輸出日期的月份的完整名, %t以後用b表示輸出日期的月份的簡稱
56 System.out.printf("%1$tY-%1$tB-%1$td; %2$tY-%2$tb-%2$td%n", date, dataL);
57  
58 // 如下是常見的日期組合
59 // %t以後用D表示以 "%tm/%td/%ty"格式化日期
60 System.out.printf("%1$tD%n", date);
61 //%t以後用F表示以"%tY-%tm-%td"格式化日期
62 System.out.printf("%1$tF%n", date);
63  
64  
65 // 輸出時分秒
66 // %t以後用H表示輸出時間的時(24進制),%t以後用I表示輸出時間的時(12進制),
67 // %t以後用M表示輸出時間的分,%t以後用S表示輸出時間的秒
68 System.out.printf("%1$tH:%1$tM:%1$tS; %2$tI:%2$tM:%2$tS%n", date, dataL);
69 // %t以後用L表示輸出時間的秒中的毫秒
70 System.out.printf("%1$tH:%1$tM:%1$tS %1$tL%n", date);
71 // %t以後p表示輸出時間的上午或下午信息
72 System.out.printf("%1$tH:%1$tM:%1$tS %1$tL %1$tp%n", date);
73  
74 // 如下是常見的時間組合
75 // %t以後用R表示以"%tH:%tM"格式化時間
76 System.out.printf("%1$tR%n", date);
77 // %t以後用T表示以"%tH:%tM:%tS"格式化時間
78 System.out.printf("%1$tT%n", date);
79 // %t以後用r表示以"%tI:%tM:%tS %Tp"格式化時間
80 System.out.printf("%1$tr%n", date);
81  
82  
83 // %t以後用A表示獲得星期幾的全稱
84 System.out.printf("%1$tF %1$tA%n", date);
85 // %t以後用a表示獲得星期幾的簡稱
86 System.out.printf("%1$tF %1$ta%n", date);
87  
88 // 輸出時間日期的完整信息
89 System.out.printf("%1$tc%n", date);
90 }
91 }
92  
93  
相關文章
相關標籤/搜索