1 使用before和after
Date1.before(Date2),当Date1小于Date2时,返回TRUE,当大于等于时,返回false;
Date1.after(Date2),当Date1大于Date2时,返回TRUE,当小于等于时,返回false;
public class Tet {
public static void main(String[] args) throws InterruptedException {
Date d1 = new Date();
Thread.sleep(300);
Date d2 = new Date();
System.out.println(d1.before(d2));
System.out.println(d1.after(d2));
}
}
before和after底层原理其实还是转换成为了毫秒
public class Date{
public boolean before(Date when) {
return getMillisOf(this) < getMillisOf(when);
}
public boolean after(Date when) {
return getMillisOf(this) > getMillisOf(when);
}
static final long getMillisOf(Date date) {
if (date.cdate == null || date.cdate.isNormalized()) {
return date.fastTime;
}
BaseCalendar.Date d = (BaseCalendar.Date) date.cdate.clone();
return gcal.getTime(d);
}
}
2 使用getTime() 转换成为毫秒
public class Test {
public static void main(String[] args) throws InterruptedException {
Date d1 = new Date();
//转换为毫秒
long d1Ms = d1.getTime();
Thread.sleep(300);
Date d2 = new Date();
//转换为毫秒
long d2Ms = d2.getTime();
System.out.println(d1Ms < d2Ms);
}
}
getTime() 底层也是获取了毫秒数.
public class Date{
public long getTime() {
return getTimeImpl();
}
private final long getTimeImpl() {
if (cdate != null && !cdate.isNormalized()) {
normalize();
}
return fastTime;
}
}
3 转换为字符串比较。compareTo()
将日期转换为字符串,然后使用compareTo()函数
compareTo()返回结果说明:
如果参数字符串等于此字符串,则返回值 0;
如果此字符串小于字符串参数,则返回一个小于 0 的值;
如果此字符串大于字符串参数,则返回一个大于 0 的值。
public class Test {
public static void main(String[] args) throws InterruptedException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = new Date();
//转换为字符串
String d1Str = df.format(d1);
Thread.sleep(2000);
Date d2 = new Date();
//转换为字符串
String s2Str = df.format(d2);
int ret = d1Str.compareTo(s2Str);
System.out.println(ret);
}
}
字符串转日期
SimpleDateFormat sdf = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
String ds=new String("2017-06-09 10:22:22");
Date sd=sdf.parse(ds);
技术交流
欢迎关注我的微信公众号:程序员大宝。一个乐于分享的程序员!关注免费领取架构师学习资料和精选大厂高频面试题库。