0

i don't want to compare year, months and days...it can affect the performance...is there any api for direct comparison ?

Date date1 = new Date(d1.getYear()  d1.getMonth(), d1.getDate());
Date date2 = new Date(d2.getYear(), d2.getMonth(), d2.getDate());
date1.compareTo(date2);
anubhava
  • 761,203
  • 64
  • 569
  • 643
geek
  • 11
  • 7
    By how much does it actually affect the performance? – Dave Newton Sep 11 '13 at 18:58
  • Comparing year, month, and date directly is going to be much faster than what any other api does, if you don't code for all the fringe cases. – Cruncher Sep 11 '13 at 18:59
  • 2
    All the dates in java are basically no of millisecond after a fix date, so i think simply comparing the miliseconds should be easy and straightforward, rather than doing all sort of formatting to compare. – Gyanendra Dwivedi Sep 11 '13 at 19:00
  • @gyan the compareTo for date is likely implemented with millis – Cruncher Sep 11 '13 at 19:01
  • Create your own comparator... – crush Sep 11 '13 at 19:02
  • @crush How? by comparing years, months, days? – Cruncher Sep 11 '13 at 19:03
  • Something like `Comparator myComparator = new Comparator() { public void compare(Date a, Date b) { return a.getDate() == b.getDate() ? 0 : a.getDate() > b.getDate() ? 1 : -1; };` I guess...not that this is necessary to achieve his goal. It's just an option. Definitely not the best one. – crush Sep 11 '13 at 19:05

2 Answers2

3

Date has before and after methods.

JNL
  • 4,683
  • 18
  • 29
2

You can use compare or compareTo method Read this thread which will answer you

Community
  • 1
  • 1
chiru
  • 812
  • 5
  • 17
  • 32