1.String类的静态format()方法用于创建格式化的字符串。format()方法有两种重载形式。
(1)format(String format,Object···args)
该方法使用指定的格式字符串和参数返回一个格式化的字符串,格式化后的新字符串使用本地默认的语言环境。
format:格式字符串
args:格式化字符串中由格式说明符引用的参数,如果还有格式说明符以外的参数,则忽略这些额外的参数,此参数的数目是可变的,可以为0。
(2)format(Local l,String format,Object····args)
l:格式化过程中要应用的语言环境,如果l为null,则不进行本地化。
args:格式化字符串中由格式说明符引用的参数,如果还有格式说明符以外的参数,则忽略这些额外的参数,此参数的数目是可变的,可以为0。
2.日期和时间字符串格式化
format()方法可以通过给定的特殊转换符作为参数来实现对日期和时间的格式化。
(1)日期格式化
以下是常用的日期格式转换符
示例代码:
public class Strtwo {
public static void main(String[] args) {
Date date=new Date();
//将date进行格式化
String year=String.format("%tY", date);
String month=String.format("%tB", date);
String day=String.format("%td", date);
System.out.println("今年是:"+year);//输出结果:今天是:2019
System.out.println("现在是:"+month);//输出结果:现在是:七月
System.out.println("今天是:"+day);//输出结果:今天是:13
}
}
(2)时间格式化
使用format()方法不仅可以完成日期的格式化,也可以实现时间的格式化,时间格式化转换符要比日期转换符更多也更精确,它可以将时间格式化为时、分、秒、毫秒。格式化时间的转换符如下图所示:
示例代码:
Date one=new Date();
String hour=String.format("%tH", one);
String minute=String.format("%tM", one);
String second=String.format("%tS", one);
System.out.println("当前时间为 "+hour+":"+minute+":"+second);
//输出结果:当前时间为 16:01:53
(3)格式化常见的日期时间组合
以下是常用的日期和时间的组合格式:
示例代码:
Date two=new Date();
String time=String.format("%tc", two);
String times=String.format("%tF", two);
System.out.println(time);//输出结果:星期六 七月 13 16:32:10 GMT+08:00 2019
System.out.println(times);//输出结果:2019-07-13
3.常规类型格式化
常规类型的格式化可应用于任何参数类型,以下是常规转换符:
示例代码:
String str1=String.format("%d", 240/2);
String str2=String.format("%b", 7>8);
String str3=String.format("%x", 460);
System.out.println("240除以2等于:"+str1);
System.out.println("7是否大于8:"+str2);
System.out.println("460的十六进制数是:"+str3);
运行结果截图: