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 */