-2

How to compare two dates in Java by incrementing Date?

String dt = "2008-01-01";  // Start date
String et="2008-01-10";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date startDate=sdf.parse(dt);
Date  endDate=sdf.parse(et);
Date incDate;
// dt is now the new date

do
{
    System.out.println("hey i am called.....");
    
    c.setTime(sdf.parse(dt));
    c.add(Calendar.DATE, 1);  // number of days to add
    dt = sdf.format(c.getTime());
    System.out.println("Incremet Date"+dt);
    incDate=sdf.parse(dt);
}
while(endDate.compareTo(incDate)>=0);
bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • 3
    And what exactly is your question? – OH GOD SPIDERS Aug 18 '20 at 12:27
  • 1
    First of all you should use the new date classes like LocalDate instead of the old Date/Calendar classes. Second your are always setting your c and incDate in your loop. I think you want to set it once outside your loop and compare it then. Anyway you should provide what you really want to do here? – TomStroemer Aug 18 '20 at 12:29
  • Please explain what you're trying to do. – Scratte Aug 18 '20 at 14:08
  • 1
    Don't know what and why you are doing this, just to compare dates? it's the path for future pain. Use LocaDateTime class instead. – Sachin Aug 18 '20 at 16:20

1 Answers1

1

first you should start using the newer classes like @TomStroemer pointed out.

I think you want to get the number of days between the two dates ?

LocalDate startDate = LocalDate.parse("2008-01-01");
LocalDate endDate = LocalDate.parse("2008-01-10");

Period period = Period.between(startDate, endDate);

System.out.println(period.getDays());

Should print 8 because there are 8 days between. Haven't tested that code.

See the following docs: Period: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

And really provide more details.

TyjameTheNeko
  • 116
  • 1
  • 9