1,使用Date自带方法before()方法和after()方法

        String start = new String("2021-04-23 14:23:20");
        String end=new String("2021-04-23 14:03:20");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(start);
            Date endDate = sdf.parse(end);
            boolean r1=startDate.before(endDate); 
            boolean r2=startDate.after(endDate);
            System.out.println(r1);
            System.out.println(r2);
        } catch (ParseException e) {
            e.printStackTrace();
        }

2,使用String的companyTo()方法。

        String start = new String("2021-04-23 14:23:20");
        String end=new String("2021-04-23 14:03:20");

        int i = start.compareTo(end);
        System.out.println(i);

值相等返回0,前者小于后者返回负数,前者大于后者返回正数。

3,转换date格式换成秒数比较秒数大小,getTime()方法。

        String start = new String("2021-04-23 14:23:20");
        String end=new String("2021-04-23 14:03:20");

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(start);
            Date endDate = sdf.parse(end);

            long t1 = startDate.getTime();
            long t2 = endDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

 

另日期和String的回转方法

1,日期类型转换为String类型

Date dt=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dtStr=sdf.format(dt);

2,String类型转换为Date类型

String dtStr="2020-03-01 12:09:23";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt=sdf.parse(dtStr);

 

 posted on 2021-04-23 15:14  会飞的金鱼  阅读(1353)  评论(0)    收藏  举报