参考博文:
Java 字符串格式化详解
Formatter是一个对常规类型和时间类型格式化输出的类. 本文只展示字符串和时间日期的格式化, 其它类型的转换可参考上面的博文。
String.format就是封装了对Formatter方法的调用, 所以本文也可以当做如何使用String.format.
public static String format(String format, Object... args) // 默认本地化输出
public static String format(Locale l, String format, Object... args) // 指定地域
一、常规类型格式化
格式: %[argument_index$] [flags] [width] [.precision] conversion
-conversion 是用来表示如何格式化参数的字符
-rgument_index 可以指定使用第几个参数来替换占位符
-flags是可选参数,用于控制输出的格式,比如左对齐、用逗号隔开。
-width是可选参数,用于控制输出的宽度。
-precision 是可选参数,用来限定输出的精度,用于浮点数。
conversion(必选)
// 栗子
String.format("我的名字是: %s", "谢耳朵") //我的名字是: 谢耳朵
System.out.println(String.format("%d", 1.1)); // .IllegalFormatConversionException: d != java.lang.Double
s: 将参数转化为字符串
d: 将参数格式化为十进制整数
…
%可以理解为格式化输出的标志.直白一点就是说:我要开始格式化参数咯。 |
---|
参数类型必须和conversion保持一致. 如上例, 若使用d, 则参数必须是整数. |
---|
rgument_index
// 栗子
String.format("%1$s的名字是: %2$s", "我", "谢耳朵") // 输出: 我的名字是: 谢耳朵
可以理解为要对第几个参数格式化. 因此这个参数在需要格式化多个参数的情况下使用.
flages
flages…跳过, 和数字相关的较多, 可以去看参考博文.
width
// 栗子
// 设置最小宽度为8,不满8位用0填充
String.format("%08d", 1); //输出 00000001
// 假如反过来会怎样?
String.format("%80d", 1); // 输出:
可以推测, 参数的顺序为格式:%填充值+长度
precision
precision…跳过
二、时间日期格式化
格式化时间分为:
- 时间格式化
- 日期格式化
- 时间日期格式化
格式:%[argument_index$][flags][width]conversion
1.时间格式化
对 时、分、秒 进行格式化
// 栗子
String.format("当前为%tH点", calendar) // 当前为21点
// 打印时、分、秒
String.format("当前时间为%1$tk时, %1$tM分, %1$tS秒", calendar) // 当前时间为21时, 45分, 56秒
// 输出本地化的上下午
String.format(Locale.US, "Local.US=%tp", calendar) // Local.US=pm
String.format(Locale.CHINA, "Local.CHINA=%tp", calendar) // Local.CHINA=下午
So, 格式化时间的格式:%t+转换符
转换符:
类型 | 字母 |
---|---|
小时(24小时制) | H、k |
小时(12小时制) | l、I(大写i) |
分钟 | M |
秒 | S |
毫秒 | L |
微秒 | N |
本地化的上午下午 | p |
时区 | z |
时区缩写字符串 | Z |
从1970-1-1 00:00到现在所经历的秒数 | s |
从1970-1-1 00:00到现在所经历的毫秒数 | Q |
2.日期格式化
对 年、月、日、星期 进行格式化
// 年
String.format("今年为, %tY", calendar) // 2019
// 月
String.format(Locale.US,"本月为, %tB", calendar) // September
String.format("本月为, %th", calendar) // 九月
// 日
String.format("今天是, %te", calendar) // 5
// 星期
String.format("今天是, %tA", calendar) // 星期四
转换符:
类型 | 字母 |
---|---|
年 | Y、y(年份后两位) |
月 | B、b、h、m(数字) |
当前月第几天 | e、d(不满2位数补0) |
星期 | A、a |
今年第几天 | j |
年份/100 | C |
3.时间日期格式化
结合 时间+日期 的格式化
// 时 + 分
String.format("当前时间:%tR", calendar) // 09:46
// 时+ 分 + 秒
String.format("当前时间:%tT", calendar) // 09:47:30
// 年/月/日
System.out.println(String.format("当前时间:%tD", calendar)); // 09/05/19
// 年-月-日
String.format("当前时间:%tF", calendar) // 2019-09-05
转换符:
类型 | 字母 |
---|---|
HH:MM (24小时制) | R |
HH:MM:SS (24小时制) | T |
HH:MM:SS 上/下午 | r |
月/日/年 | D |
年-月-日 | F |
星期四 九月 05 09:39:03 CST 2019 | c |