1.格式化时间日期
public static void main(String[] args) {
//时间戳(long类型的数字)
System.out.println(System.currentTimeMillis());//打印当前时间戳
long time = System.currentTimeMillis();//系统时间戳
System.out.printf("%tF %<tT%n",time);//tF代表年月日 Tt代表时分秒 %n是换行
//格式化输出用 System.out.printf();
//用时间戳计算两天前的日期
long time2 = System.currentTimeMillis() - (1000*60*60*24*2);//当前时间戳 - 两天的时间
System.out.printf("%tF %<tT%n",time2);//格式化输出两天前的时间戳
System.out.println("-----------------");
//日历类获取时间戳
Calendar time3 = Calendar.getInstance();//实例类格式化
int year = time3.get(Calendar.YEAR);//获取当前年份
System.out.println(year);//打印输出
long time4 = time3.getTimeInMillis();//日历获取当前时间戳
System.out.println(time4);//打印输出
}
2.格式化数字
public static void main(String[] args) {
//数字格式化
//数字百分比显示
NumberFormat a = NumberFormat.getPercentInstance();//获取数字百分比
System.out.println(a.format(.3));//30%
System.out.println(a.format(.47586));//保留两位小数进一 48%
//格式化货币
NumberFormat b = NumberFormat.getCurrencyInstance();//活动货币实例
b.setMinimumFractionDigits(3);//设置最小分数位数
System.out.println(b.format(1000234));//¥1,000,234.000
//DecimalFormat 是NumberFormat的子类,
DecimalFormatSymbols fs = new DecimalFormatSymbols();
fs.setGroupingSeparator(',');
DecimalFormat df = new DecimalFormat("#,###.00",fs);
//df.setMinimumFractionDigits(2);
df.setPositivePrefix("¥");
System.out.println(df.format(23422343.1954));//¥23,422,343.20
}
3.格式化字符串
public static void main(String[] args) {
//字符串格式化
String name = "张三";
int age = 18;
int id = 1020;
//%s s 代表String字符串 %d d代表10进制整数
System.out.printf("名字:%s 年龄:%d 身份:%d%n",name,age,id);
//格式化字符串 左对齐 右对齐 大写显示 小写显示
System.out.println();
System.out.printf("%n");
// - 代表左对齐
System.out.printf("%-10s%-6d%n","张三",18);
// + 代表右对齐
System.out.printf("%10s%6d%n","李四",18);
//大写S输出大写HELLOWORLD
//小写s输出小写helloworld
System.out.printf("%S %<s%n","helloworld");
}