Java - Date formatting help plz
Hey all, I am working on a program for class and I need to have the user input a date in a format such as "09/22/1988" and then I need that date to be formatted into something like this "Saturady, September 22, 1988". I have been using the java.util.date class for this, and this is what I have so far.
// Prompts user for birthday
temp = JOptionPane.showInputDialog("Enter your birthday(mm/dd/yyyy): ");
// Formats the given date
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
Date convertedDate = sdf.parse(temp);
temp2 = sdf.format(temp);
JOptionPane.showMessageDialog(null, "You were born on: " + temp);
I am stuck here, before I even compile or run the program I get the error under this line "> Date convertedDate = sdf.parse(temp); and it says "Unhandled exception type ParseException"
Could anyone point out what I'm doing wrong? I have been working on this for a couple of days and cannot figure out the proper syntax. Thank you all in advance!
To start with, I have never used Java in my life, so I'm probably wrong.
That being said, I used everyone's favorite search engine and found an example using the java.date.util class. The error in your code seems to happen at sdf.parse(), and the code sample uses sdf.format. So, I guess, try changing that and see if it will get farther. Also, it looks as if the sample was using a Calendar object… you might want to make sure that the Calendar object and the user input will share a similar format, just in case the sdf.Format() expects a certain pattern.
Oh, and the example was at:
Thanks for the response, I figured out that I needed to use the parse and all that good stuff later on, but then I had another error which again, I managed to figure out. But now I'm getting yet ANOTHER error. Here is the error…
"Exception: java.text.ParseException: Unparseable date: 1988-09-22".
Here is my new code that I am using…
temp = JOptionPane.showInputDialog("Enter your birthday(yyyy-MM-dd): ");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy, MM, dd");
// Formats the given date
SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
try{
Date bday = sdf.parse(temp);
temp2 = sdf2.format(bday);
JOptionPane.showMessageDialog(null, "You were born on: " + temp2);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Exception: " + e);
}
Any ideas why? Thanks again! This is a huge help.
r3drock3t88 wrote: "Exception: java.text.ParseException: Unparseable date: 1988-09-22".
Right here:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy, MM, dd");
// Formats the given date
You're using commas, so it can't parse… it's looking for hyphens. The format string should be "yyyy-MM-dd". At least, that's how it seems to me…