美文网首页
Java如何比较日期类型

Java如何比较日期类型

作者: 张伯函 | 来源:发表于2014-06-12 11:46 被阅读898次

    这里介绍Java比较两个日期类型三个例子:

    Date.compareTo()

    一个经典的方法比较两个日期类型。

    the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");
    
        System.out.println(sdf.format(date1));
        System.out.println(sdf.format(date2));
    
        if (date1.compareTo(date2) > 0) {
            System.out.println("Date1 is after Date2");
        } else if (date1.compareTo(date2) < 0) {
            System.out.println("Date1 is before Date2");
        } else if (date1.compareTo(date2) == 0) {
            System.out.println("Date1 is equal to Date2");
        } else {
            System.out.println("How to get here?");
        }
    }
    

    Date.before(), Date.after() and Date.equals()

    这是一个对用户更友好的方法去比较两个日期

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");
    
        System.out.println(sdf.format(date1));
        System.out.println(sdf.format(date2));
    
        if (date1.after(date2)) {
            System.out.println("Date1 is after Date2");
        }
    
        if (date1.before(date2)) {
            System.out.println("Date1 is before Date2");
        }
    
        if (date1.equals(date2)) {
            System.out.println("Date1 is equal Date2");
        }
    }
    

    Calender.before(), Calender.after() and Calender.equals()

    最常用的方法去比较两个日期java.util.Calendar

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");
    
        System.out.println(sdf.format(date1));
        System.out.println(sdf.format(date2));
    
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
    
        if(cal1.after(cal2)){
            System.out.println("Date1 is after Date2");
        }
    
        if(cal1.before(cal2)){
            System.out.println("Date1 is before Date2");
        }
    
        if(cal1.equals(cal2)){
            System.out.println("Date1 is equal Date2");
        }
    
    }
    

    来源:How To Compare Dates In Java

    相关文章

      网友评论

          本文标题:Java如何比较日期类型

          本文链接:https://www.haomeiwen.com/subject/nightttx.html