0

I'm trying to use a for loop through iterate through a range of dates, and I was going to increment the start date using plusDays, but I get "cannot resolve method plusDays in Date". Here is my code:

   for(Date date = finalSD; date.before(finalED); date = date.plusDays(1)){
            myBookings.put(finalSD,fac);
        }
champ0774
  • 33
  • 1
  • 6
  • 1
    `plusDays` is a method of `LocalDate`, not `Date`. – Mureinik Apr 27 '21 at 14:21
  • 3
    `java.util.Date` does not have this function, you must switch to LocalDate from `java.time` – Med Elgarnaoui Apr 27 '21 at 14:22
  • @Mureinik is there a method for Date then, since i want to increment from a given start date? – champ0774 Apr 27 '21 at 14:23
  • 1
    I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also `LocalDate` is better suited for a start date. And no, there is no such method for `Date`. You will need one conversion or another, and I recommend the conversion to some type from java.time. – Ole V.V. Apr 27 '21 at 14:53
  • 1
    @OleV.V. yeah changed everything to LocalDate type and managed. Thanks! – champ0774 Apr 27 '21 at 15:09

2 Answers2

0

java.util.Date is not java.time.LocalDate

java.util.Date does not have a plusDays(1L) function:

So if you work with Date you can increment using :

Date dt = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(dt); 
c.add(Calendar.DATE, 1);
dt = c.getTime();

or you just use java.time as :

LocalDate today = LocalDate.now() ;
LocalDate tomorrow = today.plus(1) ;

take a look at this post

Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35
0

Yea this all about time zones etc. That is the reason why it's so complicated

    Date finalSD = new Date();
    Date finalED = new Date();
    LocalDate localFinalSD = LocalDate.from(finalSD.toInstant());
    LocalDate localFinalED = LocalDate.from(finalED.toInstant());
    for(LocalDate date = localFinalSD; date.isBefore(localFinalED); date =  date .plusDays(1)){
        myBookings.put(finalSD,fac);
    }
  • 1
    I’d bewre of `LocalDate.from(finalSD.toInstant())`. Not in all time zones will it give you the day that you think is in the `Date`. I suggest `finalSD.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()` instead. Similar for end date. Otherwise a good answer. – Ole V.V. Apr 27 '21 at 16:34