3

When running through the below code I am getting an UNPARSABLE DATE EXCEPTION.

How do I fix this?

   package dateWork;

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

    public class DateCreation {

        /**
         * @param args
         */
        public static void main(String[] args) {

            String startDateString = "2013-03-26";
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
            Date startDate=null;
            String newDateString = null;
            try 
            {
                startDate = df.parse(startDateString);
                newDateString = df.format(startDate);
                System.out.println(startDate);
            } catch (ParseException e) 
            {
                e.printStackTrace();
            }
        }

    }
2
  • 1
    hint you have 2 formats of date in there, but only one SimpleDateFormat Commented Apr 2, 2013 at 9:14
  • 1
    Try -: String startDateString = "2013-03-26"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Commented Apr 2, 2013 at 9:18

4 Answers 4

12

You used wrong dateformat for month, also you should use the same delimiter as in your date.

If you date string is of format "2013/01/03"

use the same delimiter / for the pattern "yyyy/MM/dd"

If your date string is of format "2013-01-03"

use the same delimiter '-' in your pattern "yyyy-MM-dd"

    DateFormat df = new SimpleDateFormat("yyyy/mm/dd"); 

should be

    DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 

From SimpleDateFormat Doc

MM---> month in an year

mm---> minutes in hour

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

Comments

1

MM instead of mm

- instead of / ie yyyy-MM-dd as you are using - in date string

Comments

1
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 

you are using different pattern than what you are parsing.

either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); or this as String startDateString = "2013/03/26";

also look this article

Comments

0

pass same format string in constructor of SimpleDateFormat("yyyy-mm-dd")

as your string date is "2013-03-26"

if your date is "2013/03/26" use

SimpleDateFormat("yyyy/mm/dd")

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.