user4168341
user4168341

Reputation:

Bug parsing text to a calendar date

I've read through a lot of past posts and it appears I'm doing everything correctly, but the calendar is parsing the string incorrectly for some reason. Essentially I'm taking an inputted date and parsing it to a calendar date. The println statements are for the sake of bug testing.

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-YYYY");
Calendar wholeDate = new GregorianCalendar();

System.out.println(txtMmddyyyy.getText());
System.out.println(wholeDate.MONTH + " " + wholeDate.DAY_OF_MONTH + " " + wholeDate.YEAR);

try {
    wholeDate.setTime(sdf.parse(txtMmddyyyy.getText()));
} catch (ParseException e3) {
    System.out.println("Failure");
    e3.printStackTrace();
}

System.out.println(wholeDate.MONTH + " " + wholeDate.DAY_OF_MONTH + " " + wholeDate.YEAR);

When I input "05-15-2017"

-The first print statement returns "05-15-17"

-The second print statement returns "2 5 1"

-The third print statement returns "2 5 1"

I'm rather confused and am wondering if anyone knows what may be going on. Thanks.

Upvotes: 0

Views: 63

Answers (2)

AndresDLRG
AndresDLRG

Reputation: 136

As Calendar month start at 0 you are going to get the previous month

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

System.out.println(txtMmddyyyy.getText());
System.out.println(wholeDate.get(Calendar.MONTH) + " " + wholeDate.get(Calendar.DAY_OF_MONTH) + " " + wholeDate.get(Calendar.YEAR));

try {
    wholeDate.setTime(sdf.parse(txtMmddyyyy.getText()));
} catch (ParseException e3) {
    System.out.println("Failure");
    e3.printStackTrace();
}

System.out.println(wholeDate.get(Calendar.MONTH) + " " + wholeDate.get(Calendar.DAY_OF_MONTH) + " " + wholeDate.get(Calendar.YEAR));

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347184

MONTH, DAY_OF_MONTH and YEAR are constants, they don't reflect the state of the Calendar but provide you a means to interact with it. I would highly recommend that you take the time to read through the JavaDocs to better understand what those fields do and how to use them.

But, given the fact that Calendar is effectively deprecated, I'd strongly recommend you spend your time, instead, investing in learning the newer date/time classes - see Date and Time Classes for more details

Upvotes: 2

Related Questions