1.Date日期时间类
java.util.Date类
表示特定的瞬间,精准到毫秒
1000毫秒=1秒
时间原点:1970年1月1日 00:00:00
中国属于东八区,会把时间增加8个小时
1970年1月1日 08:00:00
毫秒转日期: 1天 = 24 * 60 * 60 = 86400秒
构造方法
Date的空参数构造方法:Date() 获取当前系统的日期和时间
Date的带参构造方法:Date(Long date):传递毫秒值,把毫秒转换为Date日期
成员方法
Long getTime() 将日期转换为毫秒
2.DateFormat类
Date对象和String对象进行来回切换
格式化:日期->文本
解析:文本->日期
成员方法
String format(Date date) 把Date日期 格式化为符合模式的字符串
Date parse(String source) 把符合模式的字符串 解析为Date日期
SimpleDateFormat 继承 DateFormat
构造方法:
SimpleDateFormat(String pattern)
参数:传递指定的模式
对应模式:
YYYY-MM-dd HH:mm:ss 或 YYYY年MM月dd日 HH时mm分ss秒
注意:模式中的字母不能改变,连接的符号能改变
步骤
- 创建SimpleDateFormat对象,构造方法传递指定模式
- 调用对象中的format方法,把Date日期格式化为符合模式的字符串
public static void demo1(){
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
Date date = new Date();
String text = sdf.format(date);
System.out.println(text);
}
SimpleDateFormat的parse方法将符合构造方法模式的字符 解析为Date日期
public static void demo2() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月dd日 HH时mm分ss秒");
Date date = sdf.parse("2021年08月17日 21时07分33秒");
System.out.println(date);
}