-3

I need to format a string into date using java. My String is "15th July, 2014" I need to convert it into date format like "15-07-2014"

Can anyone help me regarding that.

Mark Rowlands
  • 5,357
  • 2
  • 29
  • 41
  • I tried the following code-----But it showing error "Unparseable date: "15th July,2014" SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); String dateStr = "15th July, 2014"; Date date = dateFormat.parse(dateStr); System.out.println(date); System.out.println(dateFormat.format(date)); – user2632692 Jul 15 '14 at 08:22
  • Are your monthes names written entirely ? Or is there a limit such as "Novemb" for "November" for example ? – singe3 Jul 15 '14 at 09:00

3 Answers3

1

Here is the sample

    String dateString = "15th July, 2014";
    dateString= dateString.replace("th", "").replace("nd", "").replace("rd", "").replace("st", "");

    SimpleDateFormat formatter1 = new SimpleDateFormat("dd MMMM, yyyy");
    Date dt = formatter1.parse(dateString);

    SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MM-yyyy");
    System.out.println(formatter2.format(dt));

Read the javadoc on SimpleDateFormat for various options http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Jp Vinjamoori
  • 1,173
  • 5
  • 16
0

Use SimpleDateFormat to parse the String as a java.util.Date object; then use another SimpleDataFormat to format the date object to any format you need.

Refer to JavaDoc for details (How to set the dateformat string)

LFF
  • 228
  • 1
  • 4
0

You may need to define a SimpleDateFormat and use the parse method.

You can define almost any date pattern you want, just take a look on the pattern definition listed on javadocs

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Beware SimpleDateFormat is not thread safe.

Rafael
  • 2,521
  • 2
  • 33
  • 59