SimpleDateFormat类中的format方法和parse方法
提示:君子不忍其短,,不会则问,不能则学
一、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
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类型的对象。
parse方法可以把String型的字符串转换成特定格式的date类型,使用parse时字符串长度要和定义的SimpleDateFormat对象长度一致
parse函数是把字符串转换成日期
format
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类型的即可
format函数是把日期转换成字符串