1

HI,

I am converting String to Date format. But it returns wrong dates. for example,

String startDate = "08-05-2010"; //  (MM/dd/yyyy)

I want to convert this to "Date" object like this, 05-JUL-10

How to do that? I tried like this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
scal1.setTime(dateFormat.parse((startDate)));

but i am getting "Unparseable date:" .

4 Answers 4

4

If you want to convert a date string of one format to another format, you can use format() and parse() methods of SimpleDateFormat class

First you need to parse the string to a date object using parse() method setting the source pattern and then format the date object using format() method setting the target pattern:

SimpleDateFormat sourceFormat = new SimpleDateFormat("MM-dd-yyyy");
Date sourceFormatDate = sourceFormat.parse("08-05-2010");
SimpleDateFormat destFormat = new SimpleDateFormat("dd-MMM-yy");
String destFormatDateString = destFormat.format(sourceFormatDate);
System.out.println(destFormatDateString); // 05-Aug-10
Sign up to request clarification or add additional context in comments.

Comments

2

Unless you've left something out, it looks like you're trying to parse it with the wrong format, i.e. you have an mm-dd-yyyy, and you're trying to parse it with the format dd-MMM-yy. Try a separate date format for what you're parsing from what you're encoding.

Comments

1
SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”);
String strDate = “2007-12-25″;
Date date = null;
try {

   date = format.parse(strDate);

} catch (ParseException ex) {

   ex.printStackTrace();

}

Comments

0

The format dd-MMM-yy you use to parse the string is wrong; the format should be dd-MM-yyyy.

String startDate = "08-05-2010";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = dateFormat.parse((startDate));

Note that Date objects themselves do not have a format: a Date objects just represents a date and time value, just like an int is just a number, and doesn't have any inherent formatting information. If you want to display the Date in a certain format, you'll have to use a DateFormat object again to format it:

DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
System.out.println(dateFormat.format(date));
// output: 08-May-10

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.