DateFormat类
DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。
抽象类是不能直接使用的,所以使用它的子类,SimpleDateFormat类。
SimpleDateFormat类
SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
使用SimpleDateFormat
日期和时间模式
示例:
构造方法
// 创建SimpleDateFormat类,同时指定时间格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
方法
获取当前时间,并使用期format方法来格式化时间
// 获取当前时间
Date date = new Date();
System.out.println(date); // Fri Jul 10 09:16:19 CST 2020
// 使用format方法,将时间模式化
String date02 = simpleDateFormat.format(date);
System.out.println(date02); // 2020-07-10 09:16:19
parse() 方法,将格式化的时间解析,生成Date时间
注意,该方法有个异常抛出处理,在IDEA中使用 Alt + Ent 自动进行抛出,也就是当传入的时间不是我们在创建SimpleDateFormat时的格式时,会进行抛出异常。
// 使用parse()方法,将模式化的时间解析字符串的文本,生成 Date。
Date parse01 = simpleDateFormat.parse(date02);
System.out.println(parse01); // // Fri Jul 10 09:16:19 CST 2020