Comparing two dates using Joda time

后端 未结 9 1084
春和景丽
春和景丽 2020-12-14 14:47

I want to compare two dates, however I\'m running into trouble. 1 date is created from a java.util.date object and the other is manually crafted. The following

相关标签:
9条回答
  • 2020-12-14 15:27
    System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));
    

    or

    System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
    
    0 讨论(0)
  • 2020-12-14 15:27
    DateTimeComparator.getDateOnlyInstance().compare(obj1, obj2);
    

    obj1 and obj2 can be a String, Long, Date(java.util)... For the details see http://www.joda.org/joda-time/apidocs/index.html?org/joda/time/DateTimeComparator.html

    0 讨论(0)
  • 2020-12-14 15:31

    I stumbled into this question while looking for a comparison with today. Here's how you can compare a date to today :

    date1.toLocalDate().isBeforeNow() // works also with isAfterNow
    
    0 讨论(0)
  • 2020-12-14 15:39

    If you want to ignore time components (i.e. you want to compare only dates) you can use DateMidnight class instead of Date Time. So your example will look something like this:

    Date ds = new Date();
    DateMidnight d = new DateMidnight(ds);
    
    DateMidnight e = new DateMidnight(2012, 12, 7);
    System.out.println(d.isEqual(e));
    

    But beware, it will print "true" only today :)

    Also note that by default JDK Date and all Joda-Time instant classes (DateTime and DateMidnight included) are constructed using default timezone. So if you create one date to compare in code, but retrieve another one from the DB which probably stores dates in UTC you may encounter inconsistencies assuming you are not in UTC time zone.

    0 讨论(0)
  • 2020-12-14 15:40
    return DateTimeComparator.getDateOnlyInstance().compare(first, second);
    

    Via How to compare two Dates without the time portion?

    0 讨论(0)
  • 2020-12-14 15:46

    This is a static method which works for me.

    public static boolean isSameDay(DateTime date1, DateTime date2){
        return date1.withTimeAtStartOfDay().isEqual(date2.withTimeAtStartOfDay());
    }
    
    0 讨论(0)
提交回复
热议问题