一、DateFormat类 (抽象类)-->子类SimpleDateFormat
1. DateFormat类位于text包中,继承Format,其子类有SimpleDateFormat类
2. DateFormat 是日期/时间格式化子类的抽象类,所以不能实例化,所以要用子类SimpleDateFormat类来实现方法
二、SimpleDateFormat类
步骤:
1. 创建SimpleDateFormat对象,在构造器中写入字符串日期格式
2. 用SimpleDateFormat对象调用format方法对日期进行格式化
String format(Date date); 返回日期的字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//y表示年,M表示月,d表示月内的天,H表示一天中的小时,m表示小时中的分,s表示分钟中的秒,-可以改任意字符
String str = sdf.format(new Date()); //需要导包
结果:2018-06-08 16:22:35
三、DateFormat常用方法
1. parse(String s); 将字符串转成日期对象,如2018.1.1转成日期对象
String --> Date 用parse()
Date -->String 用format()
步骤:
1. 创建SimpleDateFormat对象,并指定日期格式
2. 调用方法parse
String str = "2015-11-15";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.parse("1995-5-6"); 这里需要抛异常,因为不能确定输入的字符串能否转成日期格式,throws Exception
结果输出Date对象,打印:Sat May 06 00:00:00 CST 1995
重要:pase(String str)中,str参数的格式必须与 SimpleDateFormat 对象中的日期格式相同。