Comparing two dates using Joda time

后端 未结 9 1120
春和景丽
春和景丽 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: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.

提交回复
热议问题