说明
在输出日期信息时,经常需要输出不同格式的日期,本实例中介绍String字符串类中的日期格式化,实例使用不同的的方式输出String类的日期格式参数值,组合这些值可以实现特殊格式的日期字符串。
关键技术
使用String类的format()方法不但可以完成日期的格式化,也可以实现时间格式化为时、分、秒、毫秒。时间日期格式化转换符如下:
代码如下:
import java.util.Date;
import java.util.Locale;
public class DateExample {
public static void main(String[] args) {
Date today = new Date();
String a = String.format(Locale.US,"%tb",today);
System.out.println("格式化后的字符串为月份的英文缩写:"+a);
String b = String.format(Locale.US,"%tB",today);
System.out.println("格式化的字符串为月份的英文全写:"+b);
String c = String.format("%ta",today);
System.out.println("格式化后的字符串为星期格式:"+c);
String d = String.format("%tA",today);
System.out.println("格式化的字符串为星期的格式:"+d);
String e = String.format("%tY",today);
System.out.println("格式化的字符串为4位年份值:"+e);
String f = String.format("%ty",today);
System.out.println("格式化后的字符串位2位年份值"+f);
String g = String.format("%tm",today);
System.out.println("格式化后的字符串位2位的月份值:"+g);
String h = String.format("%td",today);
System.out.println("格式化后的字符串为两位的日期值"+h);
String i = String.format("%te",today);
System.out.println("格式化后的字符串位1位的日期值:"+i);
}
}
注意:字符串是不可变的对象。字符串的不可变性意味着每当对字符串进行操作时,都将产生一个新的字符串对象,如果频繁的对字符串进行操作,那么会在托管堆中存在大量的无用的字符串,增加了垃圾收集器的压力,从而造成系统资源的浪费。