1

I haven't programmed in Java for many years, but I now have to change a program I wrote some time ago. In this program I need to read a QIF file and find the qif record with the maximum date (Dmm-dd-yyyy). I could not get this to work in my program so I wrote a simple test to demonstrate the problem I am having. I think there are other ways to do this, like lists and collections. But I still want to know why using SimpleDateFormat won't work. Notice in the output that this method produces the max for July but seems to ignore all August dates.

Thanks, Mike

import java.text.SimpleDateFormat; import java.util.Date;

class DateParser {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
        Date nextDate = null;
        Date maxDate = null;
        String nextStrDate = null;
        String maxStrDate = null;

        //Fill date array.
        String date[] = {"07-14-2014","07-22-2014","07-31-2014",
                         "08-01-2014","08-04-2014","08-06-2014"};

        try {
            //Start with early maximum date.
            maxDate = sdf.parse("01-01-1800");
            // Find Max date in array.
            for (int i=0; i<6; ++i) {
                nextStrDate = date[i];
                nextDate = sdf.parse(nextStrDate);
                if(nextDate.after(maxDate)){
                    maxStrDate = nextStrDate;
                    maxDate = nextDate;
                }
                System.out.println( "Next Date = " + nextStrDate);
            }
            System.out.println("\nMax Date = " + maxStrDate);
        } catch (Exception e) { 
        System.out.println("Got error:" + e);
        }
    }
}

OUTPUT

Next Date = 07-14-2014
Next Date = 07-22-2014
Next Date = 07-31-2014
Next Date = 08-01-2014
Next Date = 08-04-2014
Next Date = 08-06-2014

Max Date = 07-31-2014

2 Answers2

1

You format is incorrect, this

SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");

should be

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");

because (per the SimpleDateFormat documentation),

Letter    Date or Time Component  Presentation    Examples
...
M         Month in year           Month           July; Jul; 07
...
m         Minute in hour          Number          30
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

From the Java Docs....

m Minute in hour

What you want is

M Month in year

Change mm-dd-yyyy to MM-dd-yyyy

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366