Rookie
Rookie

Reputation: 8790

Parse exception with simpleDate Format

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);
        }

    }

Upvotes: 1

Views: 8670

Answers (4)

rizzz86
rizzz86

Reputation: 3990

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":

Upvotes: 11

Aneesh Narayanan
Aneesh Narayanan

Reputation: 3434

Try this.

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

Upvotes: 1

Edvin Syse
Edvin Syse

Reputation: 7297

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 :)

Upvotes: 5

Samir Mangroliya
Samir Mangroliya

Reputation: 40416

change slash / to dash -

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

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

Upvotes: 6

Related Questions