java时间比较3种方式

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);

技术交流

欢迎关注我的微信公众号:程序员大宝。一个乐于分享的程序员!关注免费领取架构师学习资料和精选大厂高频面试题库。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值