JDK7的日期时间类
Date类
1.概念
Date类表示时间,时间可以精确到毫秒。创建一个Date对象,其实就表示时间的对象
2.构造方法和成员方法
public class Demo1 {public static void main(String[] args) {//空参构造(将系统当前时间封装为时间对象[毫秒值])Date date1 = new Date();System.out.println(date1);//有参构造,设置时间(时间原点+时差(中国为8小时))+自己想加的时间Date date2 = new Date(3600L * 1000);System.out.println(date2);//获取时间System.out.println(date2.getTime());System.out.println(date1.getTime());long timeMillis = System.currentTimeMillis();System.out.println(timeMillis);//设置时间//如果设置为负数,则表示1970以前的时间date1.setTime(-10000000 * 1000);//date1.setTime(0L);System.out.println(date1);}
}
打印结果:
-----------------------------------------------------
Tue Jun 29 20:54:08 CST 2021
Thu Jan 01 09:00:00 CST 1970
3600000
1624971248380
1624971248393
Tue Dec 16 00:18:54 CST 1969
SimpleDateFormat类
1.作用
可以对Date对象进行格式化和解析
2.常用构造方法
public SimpleDateFormat(String pattern)
3.对Date类的应用
public class Demo2 {public static void main(String[] args) throws ParseException {//format :格式化,将date转换为字符串[看时间]Date date1 = new Date();//创建SimpleDateFormat类对象调用方法//默认格式2021/6/28 上午11:33,可在构造方法中手动设置//SimpleDateFormat sdf = new SimpleDateFormat();SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");String str = sdf.format(date1);System.out.println(str);//2021年06月28日 11时42分05秒//parse :解析,将字符串转换为data对象[计算时间]//必须填写格式,而且需要完全匹配[即sdf对象的有参格式和字符串的格式]//使用场景qq填写生日,年龄会自动更新(解析计算)Date date2 = sdf.parse(str);System.out.println(date2);}
}打印结果:
-----------------------------------------------------
2021年06月29日 20时53分37秒
Tue Jun 29 20:53:37 CST 2021