-4

Here is the code I am using:

String string = "08/07/2013".replace('/', '-');
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string);

Why does date return: "Wen Jan 3 00:00:00 EST 14"? It is not at all the date format I told it to use.

Edit: I need this format because a database I am using requires this format.

3 Answers3

4

The format you use to parse the date string, does not match it. You are using yyyy for 08.

Use the following format:

new SimpleDateFormat("dd-MM-yyyy")

and why at all are you replacing the / with -? You can build the pattern for your original string only:

String string = "08/07/2013"
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(string);

and if you want your date string in yyyy-MM-dd format, then you can format the date using DateFormat#format(Date) method:

String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);

See also:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

When you are specifying some Simple Date format using string e.g. "yyyy-MM-dd" , you have to provide your date in same format to get a date object eg. "1991-07-24" .

String mydate = "1991/07/24";
Date formattedDate = new SimpleDateFormat("yyyy/MM/dd").parse(mydate);

now if you want to convert it in any other format, you can do that by FORMATTING this date object into that perticular format..

String dateInOtherFormat = new SimpleDateFormat("dd-MMM-yyyy").format(formatteddate);

and the output of dateInOtherFormat will be ... 24-JUL-1991 .

Bharat
  • 904
  • 6
  • 19
0

Ok my sugestion is stupid but if you need this format try this

String[] arr = "08/07/2013".split("/");
String newString = arr[2]+"-"+arr[1]+"-"arr[0];
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(newString);

NOTE If your original strin is in format "MM/dd/YYYY use this:

String newString = arr[2]+"-"+arr[0]+"-"arr[1];
Dimitar Pavlov
  • 300
  • 3
  • 10