参考:
http://swiftlet.net/archives/1279
因为在设置格式化模板的时候,会使用占位符来表示字符串的格式,所以要注意一下各个占位符表示的含义。
y 年
M 年中的月份
D 年中的天数
d 月份中的天数
H 一天中的小时数(0-23)
h am/pm 中的小时数(1-12)
m 小时中的分钟数
s 分钟中的秒数
S 毫秒数
SimpleDateFormat构造方法
首先需要使用SimpleDateFormat类的构造函数设置格式化模板。如使用构造方法:public SimpleDateFormat(String pattern);pattern(格式化模板)对于parse方法和format方法的意义各不相同。具体来说,对于parse方法,则表示要解析的字符串应当具有何种格式,不符合则无法解析,若字符串同格式化模板指定的一致,则将此格式的String转为Date类型对象;而对于format方法,表示以哪种格式将Date对象格式化为String。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
下面我们来看看具体的代码加深理解。
parse
parse方法声明如下:
public Date parse(String source) throws ParseException;
public static void testParse() {
String str = "2013-01-21 15:10:20";
Date date=null ;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = sdf.parse(str);
System.out.println(date);
System.out.println(date.getTime());
} catch (ParseException e) {
System.out.println(e.getMessage());
}
}
需要注意的是,str的格式必须与构造器所指定的格式化模板一样。因为这是在SimpleDateFormat对象将此格式的字符串转为Date类型的对象。如果2者格式不一致则无法解析,所提示的信息为:Unparseable date: “2013-01-21 15:10:20”;也就无法得到Date类型的对象。
format
format方法声明如下:
public final String format(Date date)
public static void testFormat() {
SimpleDateFormat dateformat=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 ");
Date d = new Date();
String a=dateformat.format(d);
System.out.println("new Date() = "+d);
System.out.println("时间:"+a);
}
而format方法则只需要指定格式化模板即可,至于format方法中传入的参数是Date类型的即可。