1

I am trying to convert date from one format to other format but the following code is giving me the exception: please help

public class Formatter {
        public static void main(String args[]) {

            String date = "12-10-2012";
            try {
                Date formattedDate = parseDate(date, "MM/dd/yyyy");
                System.out.println(formattedDate);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public static Date parseDate(String date, String format)
                throws ParseException {
            SimpleDateFormat formatter = new SimpleDateFormat(format);
            return formatter.parse(date);
        }

    }
0

4 Answers 4

11

To convert from "MM-dd-yyyy" to "MM/dd/yyyy" you have to do as follows:

SimpleDateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
Date date = format1.parse("12-10-2012");
System.out.println(format2.format(date));

If you input "12-10-2012" then output will be "12/10/2012":

Sign up to request clarification or add additional context in comments.

Comments

6

change slash / to dash -

MM-dd-yyyy instead of MM/dd/yyyy

it should be Date formattedDate = parseDate(date, "MM-dd-yyyy");

Comments

5

Your format uses slashes (/) but the date you supply uses dashes (-). Change to:

Date formattedDate = parseDate(date, "MM-dd-yyyy");

And you should be good :)

Comments

1

Try this.

Date formattedDate = parseDate(date, "MM-dd-yyyy");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.