一、涉及类
日期篇这里介绍三个类:java.text.SimpleDateFormat、java.util.Date、java.sql.Timestamp。
Date类是JAVA日期相关处理类;
Timestamp英文名即时间戳,项目中使用mysql,存储日期统一用TIMESTAMP类型,这个类型对应JAVA的Timestamp类,所以Timestamp类也经常被用到。另外,观察源码可知Timestamp类继承Date类;
SimpleDateFormat则是Date、Timestamp与String进行转换的中间过渡类。
二、获得当前时间
1、获得当前时间戳:
原始方法是System.currentTimeMillis(); 返回long类型的时间戳
2、Date类获得当前时间:
new Date();
观察源码,无参构造的方法体为this(System.currentTimeMillis());,即获得当前时间戳然后调用 public Date(long date)构造方法
3、Timestamp类获得当前时间:
new Timestamp(System.currentTimeMillis());
观察源码,Timestamp也像Date一样有个long类型时间戳形参的构造方法,但是它不像Date一样有无参构造,所以获得Timestamp类的当前时间的方法为new Timestamp(System.currentTimeMillis());
三、Date、Timestamp与String间的转换 及 Date与Timestamp两者间的转换
1、对于Date、Timestamp与String间的转换 ,首先要定好转换的String的格式,通过SimpleDateFormat的构造方法构造,譬如:SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2、Date、Timestamp -> String
上面生成定好String格式的format对象之后,调用String format(Date date)方法,开头说过Timestamp继承Date所以也适用该方法
3、String -> Date、Timestamp
上面生成定好String格式的format对象之后,调用Date parse(String source)方法,即可得到对应的Date类型。由于Date是父类所以不能这样由String转为Timestamp,Timestamp自身带有Timestamp valueOf(String s)方法,但是调用时注意传入的String需要满足一定的格式要求,不然会报java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]的错误
4、Date -> Timestamp
利用String作为中间桥梁,即Date -> String -> Timestamp;而Timestamp本身即继承Date,所以不存在Timestamp -> Date一说。
四、Date、Timestamp比较大小
本质都是通过获取时间戳用>、<、==比较大小
1、Date比较大小
Date实现了Comparable<Date>接口,调用int compareTo(Date anotherDate);可比较大小。观察源码可知核心也是通过获取两个Date对象的时间戳进行比较
2、Timestamp比较大小
调用Timestamp自带的long getTime()方法可获得该Timestamp对象的时间戳进行比较大小
参考文章列表: