格式化类Format

1.DateFormat

日期格式化

SimpleDateFormat(String pattern)

使用给定模式 SimpleDateFormat并使用默认的 FORMAT语言环境的默认日期格式符号。

// SimpleDateFormat(String pattern) 
// 使用给定模式 SimpleDateFormat并使用默认的 FORMAT语言环境的默认日期格式符号。 
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
System.out.println(date);
// format(Date date) 
// 将给定的 Date成日期/时间字符串,并将结果追加到给定的 StringBuffer 
String date1 = dateFormat.format(date);
System.out.println(date1);
/*输出为
 *Tue Sep 28 20:17:25 CST 2021
 *2021-09-28
 */

parse(String text) 从字符串中解析文本以产生一个 Date

// parse(String text) 从字符串中解析文本以产生一个 Date 
Date date2 = dateFormat.parse(date1);
System.out.println(date2);
/*输出为
 *Tue Sep 28 00:00:00 CST 2021
 */

E表示日期中的星期,a表示上/下午,H表示24制小时,h表示12制小时,m表示分钟,s表示秒,S表示毫秒

// E表示日期中的星期
dateFormat = new SimpleDateFormat("yyyy-MM-dd E");
System.out.println(dateFormat.format(date));
// a表示上/下午,H表示24制小时,h表示12制小时,m表示分钟,s表示秒,S表示毫秒
dateFormat = new SimpleDateFormat("yyyy-MM-dd E a HH / hh:mm:ss:S");
System.out.println(dateFormat.format(date));
/*输出为
 *2021-09-28 星期二
 *2021-09-28 星期二 下午 20 / 08:17:25:509
 */

2.NumberFormat/DecimalFormat

数字格式化NumberFormat/DecimalFormat类

财务数字格式化

// 数字格式化NumberFormat/DecimalFormat类
// 财务数字格式化
double d = 1234567.890;
// #表示有效数字,且最后一位会做四舍五入操作
DecimalFormat decimalFormat = new DecimalFormat("¥###,###,###.##");
System.out.println(decimalFormat.format(d));// ¥1,234,567.89
/*输出为
 *¥1,234,567.89
 */

0表示无论有无效都会显示

// 0表示无论有无效都会显示
decimalFormat = new DecimalFormat("¥000,000,000.000");
System.out.println(decimalFormat.format(d));// ¥001,234,567.890
/*输出为
 *¥001,234,567.890
 */

parse(String source) 从给定字符串的开头解析文本以产生一个数字

// parse(String source) 从给定字符串的开头解析文本以产生一个数字
String s = "¥001,234,567.890";
System.out.println(decimalFormat.parse(s));// 1234567.89
/*输出为
 *1234567.89
 */

3.MessageForma

文本格式化 MessageFormat类

// 文本格式化
// MessageFormat类
String message = "今天是{0,date},现在是{0,time},我是{1,number}";
MessageFormat messageFormat = new MessageFormat("Date,String");
System.out.println(messageFormat.format(message,new Date(),999));
// 今天是2021-9-28,现在是20:17:25,我是999
/*输出为
 *今天是2021-9-28,现在是20:17:25,我是999
 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值