-3

Its not pretty but I'm trying to run an API call for a select date range. For some reason I'm not breaking out of my while loop. Hopefully someone can tell me what I'm doing wrong. Its pretty simple code I think.

    String modifiedStartDate;
    String modifiedEndDate;
    // Setup Initial Dates
    Calendar c = Calendar.getInstance();
    c.set(2022, 0, 1);
    date = c.getTime();
    modifiedStartDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
    c.add(Calendar.DATE, 1);
    date = c.getTime();
    modifiedEndDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
    while (modifiedEndDate != "2022-01-04"){
        System.out.println("Start: " + modifiedStartDate);
        System.out.println("Start: " + modifiedEndDate);
        c.add(Calendar.DATE, 1);
        date = c.getTime();
        modifiedStartDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
        c.add(Calendar.DATE, 1);
        date = c.getTime();
        modifiedEndDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
        
    }

The output keeps going indefinitely; see below Start: 2022-01-01 Start: 2022-01-02 Start: 2022-01-03 Start: 2022-01-04 Start: 2022-01-05 Start: 2022-01-06 Start: 2022-01-07 Start: 2022-01-08 and on and on and on :)

skigdmg
  • 1
  • 2
  • 2
    When working with strings you should never use `string1 == string2` or `string1 != string2` instead use `string1.equals(string2)` or `!string1.equals(String2)`. The short version of the issue is that the `.equals()` methods checks specifically if the contents of a string match, but `==` checks for object equality, because under the hood in java `"2022-01-04"` is not actually the same object as `new SimpleDateFormat("yyyy-MM-dd").format(date);`, the first value is created at compile-time, and the other is created at runtime, and they will never be the same object. – sorifiend May 20 '22 at 03:22
  • 2
    Stop using outdated classes like java.util.Date, Calendar and SimpleDateFormat. Use the modern java.time API. – Jens May 20 '22 at 04:40
  • I too strongly recommend you don’t use `Calendar` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 20 '22 at 06:33
  • [See for yourself how much simpler this goes with java.time.](https://ideone.com/d3UXHi) – Ole V.V. May 20 '22 at 10:53

0 Answers0