格式化字符串

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);

运行结果截图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值